스키마 함수
스키마 함수PHP Functions via Schema

PHP Functions via Schema

Included in the “Power Extensions” bundle

이 확장 기능은 프로그래밍 언어(PHP 등)에 일반적으로 존재하는 기능을 공개하는 필드와 디렉티브를 GraphQL 스키마에 추가합니다.

설명

함수 필드와 디렉티브는 데이터를 가져온 후 조작하는 데 유용합니다. 필요에 따라 필드 값을 변환하고, 강력한 데이터 가져오기/내보내기 기능을 제공합니다.

다양한 함수 필드와 디렉티브를 포함하는 다음 쿼리는:

{
  _intAdd(add: 15, to: 56)
  _intArraySum(array: [1, 2, 3, 4, 5])
 
  _arrayJoin(array: ["Hello", "to", "everyone"], separator: " ")
  _arrayItem(array: ["one", "two", "three", "four", "five"], position: 3)
  _arraySearch(array: ["uno", "dos", "tres", "cuatro", "cinco"], element: "tres")
  _arrayUnique(array: ["uno", "dos", "uno", "tres", "cuatro", "dos", "cinco", "dos"])
  _arrayMerge(arrays: [["uno", "dos", "uno"], ["tres", "cuatro", "dos", "cinco", "dos"]])
  _arrayDiff(arrays: [["uno", "dos"], ["tres", "cuatro", "dos"]])
  _arrayAddItem(array: ["uno", "dos"], value: "tres")
  _arraySetItem(array: ["uno", "dos"], index: 0, value: "tres")
  _arrayKeys(array: ["uno", "dos", "tres"])
  _arrayLength(array: ["uno", "dos", "tres"])
 
  _strRegexFindMatches(regex: "/https?:\\/\\/([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,})/", string: "In website https://gatographql.com there is more information")
  
  _strReplace(search: "https://", replaceWith: "http://", in: "https://gatographql.com")
  _strReplaceMultiple(search: ["https://", "gato"], replaceWith: ["http://", "dog"], in: "https://gatographql.com")
  _strRegexReplace(searchRegex: "/^https?:\\/\\//", replaceWith: "", in: "https://gatographql.com")
  _strRegexReplaceMultiple(searchRegex: ["/^https?:\\/\\//", "/([a-z]*)/"], replaceWith: ["", "$1$1"], in: "https://gatographql.com")
  
  _strStartsWith(search: "orld", in: "Hello world")
  _strEndsWith(search: "orld", in: "Hello world")
  _strUpperCase(text: "Hello world")
  _strLowerCase(text: "Hello world")
  _strTitleCase(text: "Hello world")
 
 
  falseToTrue: _echo(value: false) @boolOpposite
  trueToFalse: _echo(value: true) @boolOpposite
  plusOne: _echo(value: 2) @intAdd(number: 1)
  objectAddEntry: _echo(value: {
    user: "Leo",
    contact: {
      email: "leo@test.com"
    }
  })
    @objectAddEntry(key: "phone", value: "+0929094229", underPath: "contact")
    @objectAddEntry(key: "methods", value: {}, underPath: "contact")
    @objectAddEntry(key: "card", value: true, underPath: "contact.methods")
  upperCase: _echo(value: "Hello world") @strUpperCase
  lowerCase: _echo(value: "Hello world") @strLowerCase
  titleCase: _echo(value: "Hello world") @strTitleCase
  append: _echo(value: "Hello world") @strAppend(string: "!!!")
  prepend: _echo(value: "Hello world") @strPrepend(string: "!!!")
  arraySplice: _echo(value: ["uno", "dos", "tres"]) @arraySplice(offset: 1)
  arraySpliceWithLength: _echo(value: ["uno", "dos", "tres"]) @arraySplice(offset: 1, length: 1)
  arraySpliceWithReplacement: _echo(value: ["uno", "dos", "tres"]) @arraySplice(offset: 1, replacement: ["cuatro", "cinco"])
  arraySpliceWithLengthAndReplacement: _echo(value: ["uno", "dos", "tres"]) @arraySplice(offset: 1, length: 1, replacement: ["cuatro", "cinco"])
  arrayUnique: _echo(value: ["uno", "dos", "uno", "tres", "cuatro", "dos", "cinco", "dos"]) @arrayUnique
  arrayMerge: _echo(value: ["uno", "dos", "uno"]) @arrayMerge(with: ["tres", "cuatro", "dos", "cinco", "dos"])
  arrayDiff: _echo(value: ["uno", "dos"]) @arrayDiff (against: ["tres", "cuatro", "dos"])
  arrayFilter: _echo(value: ["uno", "dos", null, "tres", "", "dos", []]) @arrayFilter
  objectKeepProperties: _echo(value: { user: "Leo", email: "leo@test.com" } )
    @objectKeepProperties(
      keys: ["user"]
    )
}

...다음 결과를 생성합니다:

{
  "data": {
    "_intAdd": 71,
    "_intArraySum": 15,
    "_arrayJoin": "Hello to everyone",
    "_arrayItem": "four",
    "_arraySearch": 2,
    "_arrayUnique": [
      "uno",
      "dos",
      "tres",
      "cuatro",
      "cinco"
    ],
    "_arrayMerge": [
      "uno",
      "dos",
      "uno",
      "tres",
      "cuatro",
      "dos",
      "cinco",
      "dos"
    ],
    "_arrayDiff": [
      "uno"
    ],
    "_arrayAddItem": [
      "uno",
      "dos",
      "tres"
    ],
    "_arraySetItem": [
      "tres",
      "dos"
    ],
    "_arrayKeys": [
      0,
      1,
      2
    ],
    "_arrayLength": 3,
    "_strRegexFindMatches": [
      [
        "https:\/\/gatographql.com"
      ],
      [
        "gatographql.com"
      ]
    ],
    "_strReplace": "http://gatographql.com",
    "_strReplaceMultiple": "http://doggraphql.com",
    "_strRegexReplace": "gatographql.com",
    "_strRegexReplaceMultiple": "gatographqlgatographql.comcom",
    "_strStartsWith": false,
    "_strEndsWith": true,
    "_strUpperCase": "HELLO WORLD",
    "_strLowerCase": "hello world",
    "_strTitleCase": "Hello World",
    "falseToTrue": true,
    "trueToFalse": false,
    "plusOne": 3,
    "objectAddEntry": {
      "user": "Leo",
      "contact": {
        "email": "leo@test.com",
        "phone": "+0929094229",
        "methods": {
          "card": true
        }
      }
    },
    "upperCase": "HELLO WORLD",
    "lowerCase": "hello world",
    "titleCase": "Hello World",
    "append": "Hello world!!!",
    "prepend": "!!!Hello world",
    "arraySplice": [
      "uno"
    ],
    "arraySpliceWithLength": [
      "uno",
      "tres"
    ],
    "arraySpliceWithReplacement": [
      "uno",
      "cuatro",
      "cinco"
    ],
    "arraySpliceWithLengthAndReplacement": [
      "uno",
      "cuatro",
      "cinco",
      "tres"
    ],
    "arrayUnique": [
      "uno",
      "dos",
      "tres",
      "cuatro",
      "cinco"
    ],
    "arrayMerge": [
      "uno",
      "dos",
      "uno",
      "tres",
      "cuatro",
      "dos",
      "cinco",
      "dos"
    ],
    "arrayDiff": [
      "uno"
    ],
    "arrayFilter": [
      "uno",
      "dos",
      "tres",
      "dos"
    ],
    "objectKeepProperties": {
      "user": "Leo"
    }
  }
}

함수 필드

함수 필드는 글로벌 필드이므로 GraphQL 스키마의 모든 타입에 추가됩니다. QueryRoot뿐만 아니라 Post, User 등에도 추가됩니다.

다음은 함수 필드의 목록입니다.

_and

여러 불리언 프로퍼티 간의 AND 연산 결과를 반환합니다.

_arrayAddItem

배열에 요소를 추가합니다.

_arrayCombine

배열의 요소를 키로, 다른 배열의 요소를 값으로 사용하여 JSON 객체를 생성합니다.

_arrayChunk

배열을 청크로 분할합니다.

_arrayDiff

첫 번째 배열에는 있지만 다른 어떤 배열에도 없는 요소를 모두 포함하는 배열을 반환합니다.

_arrayEncodeAsJSONString

배열을 JSON 문자열로 인코딩합니다.

_arrayFill

값으로 채워진 배열을 생성합니다.

_arrayFilter

배열에서 null 또는 빈 요소를 제거합니다.

_arrayFlipToObject

배열의 모든 숫자 키와 관련 값을 교환하여 객체를 반환합니다.

_arrayInnerJoinJSONObjectProperties

특정 프로퍼티가 두 객체에서 동일한 경우, 소스 배열의 JSON 객체 프로퍼티로 대상 배열 내의 JSON 객체를 채웁니다.

_arrayItem

배열의 지정한 위치에 있는 요소에 접근합니다.

_arrayJoin

지정한 구분자를 사용하여 배열의 모든 문자열을 결합합니다.

_arrayKeys

배열의 키를 반환합니다.

_arrayLength

배열의 요소 수를 반환합니다.

_arrayMerge

두 개 이상의 배열을 하나로 합칩니다.

_arrayPad

값을 사용하여 배열을 지정한 길이까지 채웁니다.

_arrayRandom

제공된 요소 중 하나를 무작위로 선택합니다.

_arrayRemoveFirst

배열의 첫 번째 요소를 제거합니다.

_arrayRemoveLast

배열의 마지막 요소를 제거합니다.

_arrayReverse

배열을 역순으로 뒤집습니다.

_arraySearch

배열에서 요소가 위치한 인덱스를 검색합니다. 찾은 경우 해당 위치를 반환하고, 찾지 못한 경우 false를 반환합니다.

_arraySetItem

배열의 지정한 위치에 요소를 설정합니다.

_arraySlice

배열의 일부를 추출합니다.

_arraySplice

배열의 일부를 제거하고 다른 것으로 대체합니다.

_arrayUnique

배열에서 중복된 요소를 모두 제거합니다.

_date

지정한 형식 문자열에 따라, 지정한 정수 timestamp(Unix 타임스탬프)를 사용하거나 타임스탬프가 지정되지 않은 경우 현재 시각을 사용하여 형식화된 문자열을 반환합니다. 즉, timestamp는 선택 사항이며 기본값은 time()의 값(필드 _time을 통해 제공)입니다.

_echo

입력값을 그대로 반환합니다.

_equals

필드의 결과가 특정 값과 같은지 여부를 나타냅니다.

_floatCeil

숫자를 다음으로 높은 정수로 올림합니다.

_floatDivide

한 숫자를 다른 숫자로 나눕니다.

_greaterThan

number1 > number2인지 여부를 나타냅니다.

_greaterThanOrEquals

number1 >= number2인지 여부를 나타냅니다.

_if

불리언 프로퍼티가 true이면 한 필드를 실행하고, 그렇지 않으면 다른 필드를 실행합니다.

_inArray

배열이 해당 값을 포함하는지 여부를 나타냅니다.

_intAdd

정수에 다른 정수를 더합니다.

_intArraySum

배열 내 정수 요소의 합계를 반환합니다.

_intMultiply

정수에 다른 정수를 곱합니다.

_intSubtract

한 정수에서 다른 정수를 뺍니다.

_isEmpty

값이 비어 있는지 여부를 나타냅니다.

_isNull

값이 null인지 여부를 나타냅니다.

_lowerThan

number1 < number2인지 여부를 나타냅니다.

_lowerThanOrEquals

number1 <= number2인지 여부를 나타냅니다.

_makeTime

지정한 인수에 해당하는 Unix 타임스탬프를 반환합니다. 이 타임스탬프는 Unix 에포크(1970년 1월 1일 00:00:00 GMT)부터 지정한 시각까지의 초 수를 담은 긴 정수입니다.

생략하거나 null로 설정한 선택적 인수는 로컬 날짜 및 시각에 따라 현재 값으로 설정됩니다.

_not

불리언 프로퍼티의 반대 값을 반환합니다.

_notEmpty

값이 비어 있지 않은지 여부를 나타냅니다.

_notEquals

두 값이 서로 같지 않은지 여부를 나타냅니다.

_notInArray

배열이 해당 값을 포함하지 않는지 여부를 나타냅니다.

_notNull

값이 null이 아닌지 여부를 나타냅니다.

_objectAddEntry

객체에 항목을 추가합니다.

_objectEncodeAsJSONString

객체를 JSON 문자열로 인코딩합니다.

_objectFilter

객체에서 null 또는 빈 요소를 제거합니다.

_objectFlip

JSON 객체의 키와 값을 뒤집습니다.

_objectIntersectKey

비교에 키를 사용하여 객체의 교집합을 계산합니다.

_objectKeepProperties

JSON 객체에서 특정 프로퍼티만 유지합니다.

_objectMerge

두 개 이상의 객체를 하나로 합칩니다.

_objectProperties

JSON 객체의 프로퍼티를 가져옵니다.

_objectProperty

JSON 객체에서 프로퍼티를 가져옵니다.

_objectRemoveEntry

JSON 객체에서 항목을 제거합니다.

_objectRemoveProperties

JSON 객체에서 하나 이상의 항목을 제거합니다.

_objectValues

JSON 객체의 값을 가져옵니다.

_or

여러 불리언 프로퍼티 간의 OR 연산 결과를 반환합니다.

_propertyExistsInJSONObject

JSON 객체에 프로퍼티가 존재하는지 여부를 나타냅니다.

_propertyIsSetInJSONObject

JSON 객체에 프로퍼티가 존재하고 null이 아닌지 여부를 나타냅니다.

_sprintf

문자열 내의 플레이스홀더를 지정한 값으로 대체합니다.

_strAppend

문자열 뒤에 다른 문자열을 추가합니다.

_strArrayReplace

배열 내의 문자열을 다른 문자열로 대체합니다.

_strArrayReplaceMultiple

배열 내의 문자열 목록을 다른 문자열 목록으로 대체합니다.

_strContains

문자열이 다른 문자열을 포함하는지 여부를 나타냅니다.

_strDecodeJSONObject

문자열을 JSON 객체로 디코딩하거나, 불가능한 경우 null을 반환합니다.

_strDecodeList

문자열을 배열(임의 타입)로 디코딩하거나, 불가능한 경우 null을 반환합니다.

_strEndsWith

문자열이 다른 문자열로 끝나는지 여부를 나타냅니다.

_strLength

문자열의 길이를 반환합니다.

_strLowerCase

문자열을 소문자로 변환합니다.

_strPad

다른 문자열을 사용하여 문자열을 지정한 길이까지 채웁니다.

_strPos

문자열 내 부분 문자열의 위치를 반환하거나, 찾지 못한 경우 null을 반환합니다.

_strRegexFindMatches

정규 표현식을 실행하여 문자열에서 모든 일치 항목을 추출합니다.

_strRegexReplace

정규 표현식을 실행하여 문자열을 검색하고 대체합니다.

_strRegexReplaceMultiple

정규 표현식을 실행하여 문자열들을 검색하고 대체합니다.

_strRepeat

문자열을 반복합니다.

_strReplace

문자열을 다른 문자열로 대체합니다.

_strReplaceMultiple

문자열 목록을 다른 문자열 목록으로 대체합니다.

_strReverse

문자열을 역순으로 뒤집습니다.

_strShuffle

문자열을 무작위로 섞습니다.

_strStartsWith

문자열이 다른 문자열로 시작하는지 여부를 나타냅니다.

_strStripSlashes

백슬래시가 제거된 문자열을 반환합니다. (\' 는 '가 됩니다. 이하 동일.) 이중 백슬래시 (\\)는 단일 백슬래시 (\)가 됩니다.

_strSubstr

문자열의 일부를 반환합니다.

_strTitleCase

문자열을 타이틀 케이스로 변환합니다.

_strToTime

영어 텍스트 형식의 날짜/시각 설명을 Unix 타임스탬프로 변환합니다.

_strTrim

문자열의 앞뒤에서 공백(또는 기타 문자)을 제거합니다.

_strUpperCase

문자열을 대문자로 변환합니다.

_strWordCount

문자열의 단어 수를 반환합니다.

_time

현재 시각을 반환합니다.

함수 디렉티브

다음은 함수 디렉티브의 목록입니다.

@arrayAddItem

배열에 요소를 추가합니다.

@arrayDiff

다른 배열과의 차이를 계산합니다.

@arrayFilter

배열에서 null 또는 빈 요소를 제거합니다.

@arrayMerge

배열을 다른 배열과 병합합니다.

@arrayPad

값을 사용하여 배열을 지정한 길이까지 채웁니다.

@arrayRemoveFirst

배열의 첫 번째 요소를 제거합니다.

@arrayRemoveLast

배열의 마지막 요소를 제거합니다.

@arrayReverse

배열을 역순으로 뒤집습니다.

@arraySetItem

배열의 지정한 위치에 요소를 설정합니다.

@arraySlice

배열의 일부를 추출합니다.

@arraySplice

배열의 일부를 제거하고 다른 것으로 대체합니다.

@arrayUnique

배열에서 중복된 요소를 모두 제거합니다.

@boolOpposite

불리언 값을 반대 값으로 변환합니다.

@floatDivide

필드 값을 float 숫자로 나눕니다.

@intAdd

필드 값에 정수를 더합니다.

@intMultiply

필드 값에 정수를 곱합니다.

@intSubtract

필드 값에서 정수를 뺍니다.

@objectAddEntry

JSON 객체에 항목을 추가합니다.

@objectFilter

객체에서 null 또는 빈 요소를 제거합니다.

@objectKeepProperties

JSON 객체에서 특정 프로퍼티만 유지합니다.

@objectRemoveEntry

JSON 객체에서 항목을 제거합니다.

@objectRemoveProperties

JSON 객체에서 특정 프로퍼티를 제거합니다.

@setNull

필드 값을 null로 설정합니다.

@strAppend

필드 값의 문자열 끝에 문자열을 추가합니다.

@strLowerCase

문자열을 소문자로 변환합니다.

@strPad

다른 문자열을 사용하여 문자열을 지정한 길이까지 채웁니다.

@strPrepend

필드 값의 문자열 앞에 문자열을 추가합니다.

@strRegexReplace

정규 표현식을 실행하여 문자열을 검색하고 대체합니다(PHP 함수 preg_replace 문서 참조).

@strRegexReplaceMultiple

정규 표현식을 실행하여 문자열 목록을 검색하고 대체합니다(PHP 함수 preg_replace 문서 참조).

@strRepeat

문자열을 반복합니다.

@strReplace

문자열을 다른 문자열로 대체합니다.

@strReplaceMultiple

문자열 목록을 다른 문자열 목록으로 대체합니다.

@strReverse

문자열을 역순으로 뒤집습니다.

@strShuffle

문자열을 무작위로 섞습니다.

@strStripSlashes

백슬래시가 제거된 문자열을 반환합니다. (\' 는 '가 됩니다. 이하 동일.) 이중 백슬래시 (\\)는 단일 백슬래시가 됩니다.

@strSubstr

문자열의 일부를 반환합니다.

@strTitleCase

문자열을 타이틀 케이스로 변환합니다.

@strTrim

문자열의 앞뒤에서 공백(또는 기타 문자)을 제거합니다.

@strUpperCase

문자열을 대문자로 변환합니다.

예제

함수 필드

Post.hasComments 필드가 있더라도 반대 값이 필요할 수 있습니다. 새 필드 Post.notHasComments를 만드는(PHP 코드를 편집해야 하는) 대신, Field to Input 기능을 사용하여 hasComments의 값을 not 필드에 입력함으로써 GraphQL 쿼리 내에서 항상 새 값을 계산할 수 있습니다:

{
  posts {
    id
    hasComments
    notHasComments: _not(value: $__hasComments)
  }
}

함수 필드를 여러 번 적용하여 더 복잡한 계산을 수행할 수 있습니다. 예를 들어, 다른 필드의 값을 기반으로 summary 필드를 생성하는 경우:

{
  posts {
    id
    content @remove
    shortContent: _strSubstr(string: $__content, offset: 0, length: 150) @remove
    excerpt @remove
    isExcerptEmpty: _isEmpty(value: $__excerpt) @remove
    summary: _if(
      condition: $__isExcerptEmpty
      then: $__content
      else: $__excerpt
    )
  }
}

HTTP Client 확장 기능과 결합하면 (사이트의 데이터를 기반으로) 연결할 API 엔드포인트를 동적으로 생성하고, 반환된 데이터에서 특정 필드를 추출할 수 있습니다:

{
  users(
    pagination: { limit: 2 },
    sort: { order: ASC, by: ID }
  ) {
    id
    
    # Dynamically generate endpoint for the user
    endpoint: _arrayJoin(values: [
      "https://newapi.getpop.org/wp-json/wp/v2/users/",
      $__id,
      "?_fields=name,avatar_urls"
    ])
    
    # Retrieve the endpoint data
    endpointData: _sendJSONObjectItemHTTPRequest(input: { url: $__endpoint } )
 
    # Extract specific information
    userAvatar: _objectProperty(
      object: $__endpointData,
      by: {
        path: "avatar_urls.48"
      }
    )
  }
}

...다음 결과를 생성합니다:

{
  "data": {
    "users": [
      {
        "id": 1,
        "endpoint": "https://newapi.getpop.org/wp-json/wp/v2/users/1?_fields=name,avatar_urls",
        "endpointData": {
          "name": "leo",
          "avatar_urls": {
            "24": "https://secure.gravatar.com/avatar/b28085726ee66e49f08be16ad668efd5?s=24&d=mm&r=g",
            "48": "https://secure.gravatar.com/avatar/b28085726ee66e49f08be16ad668efd5?s=48&d=mm&r=g",
            "96": "https://secure.gravatar.com/avatar/b28085726ee66e49f08be16ad668efd5?s=96&d=mm&r=g"
          },
          "_links": {
            "self": [
              {
                "href": "https://newapi.getpop.org/wp-json/wp/v2/users/1"
              }
            ],
            "collection": [
              {
                "href": "https://newapi.getpop.org/wp-json/wp/v2/users"
              }
            ]
          }
        },
        "userAvatar": "https://secure.gravatar.com/avatar/b28085726ee66e49f08be16ad668efd5?s=48&d=mm&r=g"
      },
      {
        "id": 2,
        "endpoint": "https://newapi.getpop.org/wp-json/wp/v2/users/2?_fields=name,avatar_urls",
        "endpointData": {
          "name": "themedemos",
          "avatar_urls": {
            "24": "https://secure.gravatar.com/avatar/7554514b65216821eeacde0fdcd6c6e6?s=24&d=mm&r=g",
            "48": "https://secure.gravatar.com/avatar/7554514b65216821eeacde0fdcd6c6e6?s=48&d=mm&r=g",
            "96": "https://secure.gravatar.com/avatar/7554514b65216821eeacde0fdcd6c6e6?s=96&d=mm&r=g"
          },
          "_links": {
            "self": [
              {
                "href": "https://newapi.getpop.org/wp-json/wp/v2/users/2"
              }
            ],
            "collection": [
              {
                "href": "https://newapi.getpop.org/wp-json/wp/v2/users"
              }
            ]
          }
        },
        "userAvatar": "https://secure.gravatar.com/avatar/7554514b65216821eeacde0fdcd6c6e6?s=48&d=mm&r=g"
      }
    ]
  }
}

함수 디렉티브

다음 쿼리가:

query {
  posts {
    title
  }
}

...다음 결과를 생성하는 경우:

{
  "data": {
    "posts": [
      {
        "title": "Hello world!"
      },
      {
        "title": "lovely weather"
      }
    ]
  }
}

...다음 쿼리는:

query {
  posts {
    title @strUpperCase
  }
}

...다음 결과를 생성합니다:

{
  "data": {
    "posts": [
      {
        "title": "HELLO WORLD!"
      },
      {
        "title": "LOVELY WEATHER"
      }
    ]
  }
}