repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
loginsinex/smb2
smb2/h/GUI/Dialogs/Worlds/cgameworlds.h
typedef struct _tagNES_LEVEL_SET { int id; BOOL fNew; BOOL fDeleted; std::vector<BYTE> vRoomsList; } NES_LEVEL_SET, *PNES_LEVEL_SET; class CWorldsDlgs: public CDialog { CFileLoader & m_file; void OnPreInit(CDialogTemplate & d); virtual void OnPreInitSheet(CDialogTemplate & d) PURE; protected: CFileLoader & File(); CWorldsDlgs(HINSTANCE hInstance, CFileLoader & file); void FillGradientRect(HDC hDC, RECT rc, COLORREF clr1, COLORREF clr2, BOOL fVertical = TRUE); }; class CWorldsLevelsDlg: public CWorldsDlgs { CBufView *m_pBufView; BYTE m_bWorlds[8]; CFont m_fntCtl; struct { HBRUSH hBrushHl; // hilite HBRUSH hBrushBd; // game bounds COLORREF clrGradient1; // gradient for background COLORREF clrGradient2; BOOL fBounds[2][2]; // game bounds buttons states. 0 - left, 1 - right BOOL fWorlds[2][7]; // worlds buttons states. 0 - left, 1 - right RECT rcBounds[2][2]; // buttons rect RECT rcWorlds[2][7]; struct { RECT * prc; BOOL * pfState; struct { BOOL fBounds; BOOL fRight; BYTE bWorld; } type; } sel; } m_ctlState; void OnInit(LPARAM lParam); void OnPreInitSheet(CDialogTemplate & d); INT PSOnApply(); static LRESULT CALLBACK BVProc(HWND, UINT, WPARAM, LPARAM, PVOID); LRESULT CtlProc(CBufView *, UINT, WPARAM, LPARAM); void OnCtlMouseEvent(UINT uMouseEvent, SHORT x, SHORT y); void CtlDraw(); void OnCtlClick(BOOL fBounds, BOOL fRight, BYTE world); void LoadData(); void StoreData(); public: CWorldsLevelsDlg(HINSTANCE hInstance, CFileLoader & file); ~CWorldsLevelsDlg(); }; class CWorldsDataDlg: public CWorldsDlgs { CListView m_lv; CComboBox m_cb; CFont m_fnList; std::vector<NES_LEVEL_SET> m_vLevelsSets; std::vector<NES_LEVEL_SET> m_vEnemiesSets; void OnPreInitSheet(CDialogTemplate & d); void OnInit(LPARAM lParam); INT_PTR OnNotify(LPNMHDR lpnm); void OnButton(USHORT uId); INT PSOnApply(); void LoadData(); void StoreData(); void ListRooms(); void MoveRoom(); void CreateBucket(); void FindRoom(); public: CWorldsDataDlg(HINSTANCE hInstance, CFileLoader & file); }; // helpers dialogs class CChooseBucketDlg: public CDialog { CComboBox m_cb; void OnPreInit(CDialogTemplate & d); void OnInit(LPARAM lParam); void OnOK(); struct { BOOL fEnemiesBuckets; int iSelected; std::vector<NES_LEVEL_SET> vList; } m_buckets; public: CChooseBucketDlg(HINSTANCE hInstance, std::vector<NES_LEVEL_SET> & vList, BOOL fEnemiesBucket, int iSelected); int GetSelected(); }; class CNewBucketDlg: public CDialog { void OnPreInit(CDialogTemplate & d); void OnInit(LPARAM lParam); void OnOK(); BOOL m_fEnemies; public: CNewBucketDlg(HINSTANCE hInstance, BOOL fEnemies); BOOL GetSelection(); }; class CFindRoomDlg: public CDialog { CComboBox m_cb; void OnPreInit(CDialogTemplate & d); void OnInit(LPARAM lParam); void OnOK(); BOOL m_fEnemies; BYTE m_bRoom; public: CFindRoomDlg(HINSTANCE hInstance); BOOL GetSelection(BYTE & bRoom); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/ctabcontrol.h
class CTabControl: public CControl { public: void AddItem(LPCTSTR pszText, LPARAM lParam = 0); void Param(int i, LPARAM lParam); LPARAM Param(int i); INT GetCurSel(); void SetCurSel(INT i); INT ItemsCount(); void Adjust(HWND hWnd); void DeferAdjust(HDWP hDwp, HWND hWnd); void SetText(int i, LPCTSTR pszText); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Editor/clevelinfodlg.h
class CLevelInfoDlg: public CDialog { CNesEditor & m_pvEditor; CFileLoader & m_File; CTrackBar m_tbLength; CTrackBar m_tbBgSet; CTrackBar m_tbBgType; CTrackBar m_tbObjType; CTrackBar m_tbPallete; CTrackBar m_tbEnemyPallete; CComboBox m_cbMusic; CLvlDraw * m_pLevel; CNesEditor m_vEditor; DWORD m_dwCurLevel; VOID OnInit(LPARAM lParam); VOID OnOK(); VOID LoadLevelSample(); INT OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & pHandle); INT_PTR OnTrackbar(LPNMHDR lpnm); VOID OnButton(USHORT uId); public: CLevelInfoDlg(HINSTANCE hInstance, CNesEditor & pvEditor, DWORD dwCurLevel, CFileLoader & file, CNesLevel & lvl, CNesEnemyData & enm); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/ccontrol.h
class CControl { HWND m_hWnd; protected: CControl(); CControl(HWND hWnd); public: void AssignWindow(HWND hWnd); void AssignControl(HWND hWnd, USHORT uCtlId); INT_PTR cSendMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = NULL); HWND GetWindowHandle(); void Enable(BOOL bEnabled); BOOL Enable(); BOOL Visible(); void Visible(BOOL bVisible); operator HWND(); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/cbufview.h
#define BVM_GETINSTANCE ( WM_USER + 0x111 ) #define BVM_GETUPDATEAREA ( WM_USER + 0x112 ) VOID InitBufView(HINSTANCE hInstance, LPTSTR pszClass); typedef LRESULT (CALLBACK* BVPROC)(HWND, UINT, WPARAM, LPARAM, PVOID); class CBufView { HWND m_hWnd; BVPROC m_pwndProc; PVOID m_pParam; HINSTANCE m_hInstance; LPTSTR m_pszClass; CREATESTRUCT m_cs; HFONT m_hGlobalFont; HDC m_hDC; struct { SIZE sz; HDC hDCDesktop; HDC hDC; HBITMAP hBmp; HBITMAP hOldBmp; PBYTE pvBits; BITMAPINFO bmi; struct { HFONT hOldFont; HFONT hFont; } font; struct { HPEN hOldPen; HPEN hPen; } pen; struct { HBRUSH hOldBrush; HBRUSH hBrush; } brush; } m_buffer; LRESULT OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK BufViewProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); friend VOID InitBufView(HINSTANCE hInstance, LPTSTR pszClass); VOID RenderOnDevice(HDC hDC); public: CBufView(LPCREATESTRUCT lpcs); ~CBufView(); VOID SetPen(HPEN hPen, BOOL fDestroy = TRUE); VOID SetBrush(HBRUSH hBrush, BOOL fDestroy = TRUE); VOID SetFont(HFONT hFont, BOOL fDestroy = TRUE); HWND GetWindowHandle(); HDC GetBufferHandle(); VOID Refresh(); VOID Erase(HBRUSH hBrush, BOOL fDestroy = FALSE); VOID Assign(BVPROC pDlgProc = NULL, PVOID pParam = NULL); operator HDC(); operator HWND(); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cwrlditrdlg.h
class CWrldItrDlg: public CDialog { CFileLoader & m_File; CComboBox m_cbIterior[7]; VOID OnInit(LPARAM lParam); USHORT m_pData[7]; VOID LoadItems(); VOID SaveItems(); VOID SetItems(); VOID WriteItems(); INT PSOnApply(); public: CWrldItrDlg(HINSTANCE hInstance, CFileLoader & fl); };
loginsinex/smb2
smb2/h/NES/cnesfile.h
#define LOAD_PTR_NC(w) (0x0000c02c+0x94*w) #define LOAD_PTR_EC(w) (0x0000c09c+0x94*w) #define MAX_PTR_NC (LOAD_PTR_NC(7) + 128) #define MAX_PTR_EC (LOAD_PTR_EC(7) + 48) #define MAX_LEVELS 210 #define NES_PTR_LEVEL_STARTS 0x0001F768 #define NES_PTR_LEVELS1 0x0001F770 #define NES_PTR_LEVELS2 0x0001F775 #define NES_PTR_ENEMY1 0x0001F791 #define NES_PTR_ENEMY2 0x0001F796 #define NES_PTR_ENEMY3 0x0001F79B #define NES_PTR_ENEMY4 0x0001F7A0 #define NES_PTR_START 0x00010010 #define NES_PTR_EOF 0x00014010 extern const LPTSTR g_szLevelName[]; class CFileLoader { struct { CString sFilename; std::vector<BYTE> vFile; BOOL fModified; } m_File; struct { BYTE nLevel[MAX_LEVELS]; BYTE nEnemy[MAX_LEVELS]; BOOL fLoaded; } m_game; std::vector<CNesEditor*> m_vEditors; struct { std::vector<CNesLevel*> vLevel; std::vector<CNesEnemyData*> vEnemy; std::vector<BYTE> vStarts; } m_data; struct { DWORD ptrLevelStarts; DWORD ptrLevels[2]; DWORD ptrEnemies[4]; } m_ptr; void Flush(); public: CFileLoader(); ~CFileLoader(); BOOL IsLoaded(); int LoadFile(LPCTSTR pszFilename); int SaveFile(LPCTSTR pszFilename = NULL); CNesEditor & getLevelEditor(UINT level); int Read(); int Write(); BOOL LoadData(PBYTE pArray, DWORD ptr, INT iSizeOfArray); BOOL WriteData(PBYTE pArray, DWORD ptr, INT iSizeOfArray); USHORT Short(DWORD ptr); VOID Short(DWORD ptr, USHORT val); BYTE Byte(DWORD ptr); VOID Byte(DWORD ptr, BYTE val); DWORD Word(DWORD ptr); VOID Word(DWORD ptr, DWORD val); BOOL GetMemoryStatus(DWORD & systemData, DWORD & levelData, DWORD & enemyData, DWORD & occupiedSpace, DWORD & totalSpace); BOOL GetGameSets(std::vector<int> & vLevelData, std::vector<BYTE> & vRoomsLevelsList, std::vector<int> & vEnemyData, std::vector<BYTE> & vRoomsEnemiesList); BOOL SetGameSets(std::vector<int> & vLevelData, std::vector<BYTE> & vRoomsLevelsList, std::vector<int> & vEnemyData, std::vector<BYTE> & vRoomsEnemiesList); }; /* class CFileLoader { BYTE *pFile; BOOL fLoaded; BOOL fModified; DWORD dwSize; BYTE bZero; CNesTiles m_nTiles; public: struct { BYTE nc[64][16]; BYTE ec[32][12]; struct { DWORD levelPtr; DWORD enemyPtr; DWORD levelBits; DWORD levelSize; DWORD enemySize; DWORD dwDuplicate; DWORD dwDupEnemies; struct { BYTE fDirection:1; BYTE Reserved1:1; BYTE uColor:3; BYTE Reserved2:1; BYTE uEnemyColor:2; BYTE Reserved3:3; BYTE uGround:5; BYTE uLength:4; BYTE uObjectType:4; BYTE Reserved4:2; BYTE uTypeOfGround:3; BYTE Reserved5:1; BYTE uMusic:2; } levelFields; CNesLevel vLevel; CNesEnemyData vEnemy; CNesEditor vEditor; / * level bits: 0 - Horizontal scroll 1-4 - Reserved 5-7 - level colors 8-11 - Reserved 12-13 - Enemy colors 14-16 - Type of ground 17-18 - Level music 19-23 - Ground 24-27 - Level length 28-31 - Object type * / } level[210]; } m_gameData; private: BOOL CheckFile(); BOOL ReadFile(); BOOL WriteFile(); PBYTE MakeLevelList(LPDWORD lpdwSize); PBYTE MakeEnemiesList(LPDWORD lpdwSize); DWORD getEnemyLevelSize(DWORD dwLevel); DWORD getItemLevelSize(DWORD dwLevel); public: CFileLoader(); ~CFileLoader(); VOID LoadFile(HANDLE hFile); BOOL SaveFile(HANDLE hFile); BOOL IsLoaded(); BOOL IsModified(); BYTE levelValue(UINT level, UINT index); VOID levelValue(UINT level, UINT index, BYTE data); CNesLevel & getLevelItem(UINT level); CNesEnemyData & getEnemyItem(UINT level); CNesEditor & getLevelEditor(UINT level); BOOL LoadData(PBYTE pArray, DWORD ptr, INT iSizeOfArray); BOOL WriteData(PBYTE pArray, DWORD ptr, INT iSizeOfArray); }; */
loginsinex/smb2
smb2/h/GUI/Dialogs/Editor/ceditordlgs.h
<filename>smb2/h/GUI/Dialogs/Editor/ceditordlgs.h class CEntrancePtrDlg: public CDialog { int m_fCreation; BYTE m_bRequestedPtr; VOID OnInit(LPARAM lParam); VOID OnPreInit(CDialogTemplate & d); VOID OnButton(USHORT uId); public: CEntrancePtrDlg(HINSTANCE hInstance, BOOL fCreation = 0); BOOL IsFarPointer(); BYTE GetPointerParam(BYTE id); BYTE GetRequestedPtr(); VOID SetPointerData(BOOL fFarPointer, BYTE param1, BYTE param2); }; class CGroundSetDlg: public CDialog { VOID OnInit(LPARAM lParam); public: CGroundSetDlg(HINSTANCE hInstance); BYTE GroundSet(); BYTE GroundType(); VOID GroundSet(BYTE bBgSet); VOID GroundType(BYTE bBgType); }; class CItemSizeDlg: public CDialog { VOID OnInit(LPARAM lParam); public: CItemSizeDlg(HINSTANCE hInstance); BYTE GetSizeParam(); VOID SetSizeParam(BYTE bSize); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/listview.h
#define LVIS_CURSEL (LVIS_SELECTED | LVIS_FOCUSED) #define DBF_CONTROL TEXT("DBF") typedef struct _tagLISTVIEW_PARAM { WNDPROC pfnWndProc; HBITMAP hBitmap; PVOID pvBits; HDC hDC; RECT rc; HDC hDesktopDC; HBITMAP hOldBmp; BOOL fIsListView; RECT header_rc; HWND hHeader; } LISTVIEW_PARAM, *LPLISTVIEW_PARAM; void InitListView(); void InitDDControl(LPCTSTR pszClassName);
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/cglasswnd.h
#define GLASSOP TEXT("__glassctl") #define GLASSPTR(wnd) ((CGlassCtl*) GetProp(wnd, GLASSOP)) #define SETGLASS(wnd, _this) (SetProp(wnd, GLASSOP, (HANDLE) _this)) #define DELGLASS(wnd) (RemoveProp(wnd, GLASSOP)) typedef union _tagWRGB { struct { unsigned char red; unsigned char green; unsigned char blue; unsigned char alpha; } color; ULONG uColor; } WRGB, *PWRGB; class CGlassWnd; class CGlassCtl { HWND m_hWnd; WNDPROC m_pfnProc; CGlassCtl(HWND hControl, BYTE alpha, USHORT cx = 100, USHORT cy = 100); ~CGlassCtl(); static LRESULT CALLBACK CtlWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); struct { HDC hOriginalDC; HBITMAP hOldBitmap; HDC hBuffer; HBITMAP hBufferBmp; HANDLE pBuffer; PWRGB pLockedBuffer; BYTE alpha; SIZE sz; } m_gBuffer; VOID CreateBuffer(USHORT cx, USHORT cy); VOID ResizeBuffer(USHORT cx, USHORT cy); VOID ReleaseBuffer(); PWRGB Buffer(); VOID OnPaintProc(HWND hWnd, HDC hDC); PWRGB Buffer(HDC, RECT); VOID WriteToDevice(PWRGB pBuffer, HDC hDC, RECT); friend CGlassWnd; }; class CGlassWnd { HWND m_hParent; vector<CGlassCtl*> m_vCtlList; VOID SubclassChilds(HWND hParent, BYTE alpha); public: CGlassWnd(HWND hDialog, BYTE alpha = 255); ~CGlassWnd(); };
loginsinex/smb2
smb2/h/GUI/Dialogs/cleveldlg.h
<reponame>loginsinex/smb2<filename>smb2/h/GUI/Dialogs/cleveldlg.h class CMainWnd; class CLevelDlg: public CDialog { CFileLoader & m_File; CLvlDraw* m_pLevel; CListView m_lv; void OnInit(LPARAM lParam); INT_PTR OnNotify(LPNMHDR lpnm); void OnButton(USHORT uId); // events from leveleditor BOOL OnNotify_ChangeBg(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_HitTest(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_HitTestEnemy(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_Insert(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent, BOOL fInsertJarEnemy); BOOL OnNotify_Edit(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_JumpPointer(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_Delete(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_ChangeLayer(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_LevelData(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_MakeJar(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); BOOL OnNotify_ItemSelected(CNesEditor & ed, PNMLVLDRWHT p, CMainWnd * pParent); public: CLevelDlg(CFileLoader & fl, HINSTANCE hInstance); VOID CheckData(BOOL fInvalidateCanvas = FALSE); VOID SelectPos(int page, BYTE pos); }; class CNewSpaceDlg: public CDialog { BOOL m_fCreateForEnemies; DWORD m_dwLevel; std::vector<int> m_vLevelData; std::vector<BYTE> m_vRoomsLevelsList; std::vector<int> m_vEnemyData; std::vector<BYTE> m_vRoomsEnemiesList; void OnPreInit(CDialogTemplate & d); void OnInit(LPARAM lParam); void OnOK(); public: CNewSpaceDlg(HINSTANCE hInstance, std::vector<int> & vLevelData, std::vector<BYTE> & vRoomsLevelsList, std::vector<int> & vEnemyData, std::vector<BYTE> & vRoomsEnemiesList, BOOL fEnemies, DWORD dwLevel); BOOL GetSelection(std::vector<int> & vLevelData, std::vector<BYTE> & vRoomsLevelsList, std::vector<int> & vEnemyData, std::vector<BYTE> & vRoomsEnemiesList); };
loginsinex/smb2
smb2/h/GUI/Wrapper/cfont.h
class CFont { HFONT m_hFont; public: CFont(); CFont(INT iHeight, BOOL bBold, BOOL bItalic, BOOL bStriked, BOOL bUnderline, LPTSTR lpszFontFace, UINT fQuality); void Create(INT iHeight, BOOL bBold, BOOL bItalic, BOOL bStriked, BOOL bUnderline, LPTSTR lpszFontFace, UINT fQuality); void Release(); void LoadFromWindow(HWND hWndFrom, INT iHeight = -1, INT bBold = -1, INT bItalic = -1, INT bStriked = -1, INT bUnderline = -1, LPTSTR lpszFontFace = NULL, UINT fQuality = -1); HFONT Font(); operator HFONT(); ~CFont(); };
loginsinex/smb2
smb2/h/NES/nesleveldef.h
typedef struct _tagNES_ITEM_DIM { BYTE topleft; BYTE top; BYTE topright; BYTE left; BYTE right; BYTE middle; BYTE bottomleft; BYTE bottomright; } NES_ITEM_DIM, *PNES_ITEM_DIM; typedef struct _tagNES_ENEMY_DIM { BYTE xy; BYTE szxy; } NES_ENEMY_DIM, *PNES_ENEMY_DIM; typedef union _tagNES_GROUND_DIM { DWORD dwGround; struct { BYTE gr[4]; } gr; } NES_GROUND_DIM, *PNES_GROUND_DIM; typedef struct _tagNES_GROUND_BITSET { BYTE uGroundType; DWORD uGroundSet; } NES_GROUND_BITSET, *PNES_GROUND_BITSET; typedef struct _tagNES_PRIORITY_LIST { BYTE bgPriority; BYTE bObjId; // regular id BYTE bPriority; // priority. 0 - higher, 5 - lower } NES_PRIORITY_LIST, *PNES_PRIORITY_LIST; extern const NES_ITEM_DIM g_mItemDim[]; extern const NES_ITEM_DIM g_msItemDim[]; extern const NES_ENEMY_DIM g_mEnemyDim[]; extern const DWORD g_mGroundSet[]; extern const DWORD g_mvGroundSet[]; extern const NES_GROUND_DIM g_mGroundType[]; extern const NES_GROUND_DIM g_mvGroundType[]; extern const NES_PRIORITY_LIST g_mPriorityList[]; extern const NES_GROUND_DIM g_mbgPriority[]; extern const NES_GROUND_DIM g_mvbgPriority[]; extern const BYTE g_mLayerLimiter[]; extern const BYTE g_mLayerLimiting[]; extern const USHORT g_mWorldInterior[]; extern const COLORREF g_crNesColor[];
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cobjtiles.h
class CTilesDlg: public CDialog { INT OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & pHandle); protected: CFileLoader & m_File; CTilesDlg(HINSTANCE hInstance, CFileLoader & fl, LPTSTR lpszRes); ~CTilesDlg(); INT GetFX(INT iWorld); virtual VOID SetTiles(INT i) = 0; VOID LoadTiles(); struct { HIMAGELIST himl[5]; } m_Image; }; class CObjTilesDlg: public CTilesDlg { BYTE m_pTilesArray[252]; VOID OnInit(LPARAM lParam); VOID SetTiles(INT i); VOID LoadItems(); VOID SaveItems(); VOID SetItems(); VOID WriteItems(); VOID OnCommand(USHORT uCmd, USHORT uId, HWND hCtl); INT PSOnApply(); CComboBox m_cbWorld; CComboBox m_cbObj; USHORT m_cbTile[4]; public: CObjTilesDlg(HINSTANCE hInstance, CFileLoader & flLoader); ~CObjTilesDlg(); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cmiscdatadlg.h
<filename>smb2/h/GUI/Dialogs/Advanced/cmiscdatadlg.h /* typedef enum _tagNES_MISC_DATA_ENUM { nmdNone, // 0x000C77 - Amount of time needed to charge jump nmdChargeJumpTime, // 0x00102A - Number of cherries required for Starman nmdCherriesForStar, // 0x001034 - sound effect for grabbing a cherry nmdCherrySound, // 0x0010DF - Item pulled once the 1-Up flag is activated // 0x0010F2 - Sprite pulled after number of big vegetables pulled is activated // 0x0011FE - Button for opening doors // 0X001820 ~ 0X001A1C - Text for Title // 0X001892 ~ 0X0018B1 - Palettes for Title screen // 0x001AA9 - song to play at Title screen // 0x002E70 ~ 0x00309F - Empty // 0x003B70 ~ 0x00400F - Empty // 0x004099 - Sound effect from falling in 1-1 nmdFallSound, // 0x004556 - Number of enemies defeated for heart nmdEnemiesForHeart, // 0x004C4A - Panser's spitting time // 0x004C74 - Grey panser's spitting direction // 0x004D53 - Jump height on coming out of jars // 0x004F4E - Sprite Graphic to use for Heart floating // 0x004F7B - Health for Birdos nmdBirdoHealth, // 0x004FA8 - Birdo's jump height nmdBirdoJumpHeight, // 0x004FC3 - Birdo's spitting time nmdBirdoSpittingTime, // 0x004FD6 - Birdo's speed (right) nmdBirdoSpeedRight, // 0x004FDC - Birdo's speed (left) nmdBirdoSpeedLeft, // 0x004FEA - Birdo's spitting sound nmdBirdoSpittingSound, // 0x005061 - Sound a 1-up makes // 0X0050B8 - sound effect for grabbing a mushroom // 0x0050CB - Amount of time the stop watch is active nmdStopWatchTimeout, // 0x0053C7 - Jumping Ninja's 1st jump // 0x0053C8 - Jumping Ninja's 2nd jump // 0x0053C9 - Running Ninja's 1st jump // 0x0053CA - Running Ninja's 2nd jump // 0X005523 - Tweeter AI (it can follow you) // 0x00552A - Tweeter jump before the other jump // 0x00552E - Tweeter's number of jumps of first jump before the second jump // 0x005532 - Tweeter's other jump after performing the previous jump // 0x00556C - Snifit's jump height // 0x0055A3 - Snifit's spitting time // 0x005703 - Amount of time the ground shakes from a POW nmdPOWTimeEffect, // 0x005818 ~ 0x005848 - How the Doors open // 0x005ECD ~ 0x00603F - Empty // 0x00611E - Health for Claw Grip of World 5 nmdHealthClawGlip, // 0x006171 - Claw Grip's rock throwing time // 0x0061D5 - Rock speed // 0X006486 - Amount of time to fly Pidget's carpet nmdCarpetTimeout, // 0x00657F - Health for Mouser of World 1 nmdMouserHealth1, // 0x006586 - Health for Mouser of World 3 nmdMouserHealth3, // 0x0065B0 - Mouser's jump height nmdMouserJumpHeight, // 0x0065BC - Mouser's bomb holding time nmdMouserBombHoldingTime, // 0x0065F4 - Mouser's bomb throwing height nmdMouserThrowHeight, // 0x0065FB - Time before bomb explosion nmdBombTimeout, // 0x0065FF - Mouser's bomb throwing speed nmdMouserThrowSpeed, // 0x00673D - Health for Triclydes nmdTriclydeHealth, // 0x0068BB - Triclyde's spitting sound nmdTriclydeSpittingSound, // 0x006C7E - Health for Fry Guy of World 4 nmdFryGuyHealth, // 0x006FF7 - Health for Hawkmouth of World 7 nmdHawkmouthHealth, // 0x0070BB - Health for revived Hawkmouth nmdHawkmouthRevivedHealth, // 0x0070C6 - Amount of time Hawkmouth is open (before Wart) nmdHawkmouthTimeout, // 0x0071E0 - Health for Wart of World 7 nmdWartHealth, // 0x00721D - Wart's speed (left) nmdWartSpeedLeft, // 0x007223 - Wart's speed (right) nmdWartSpeedRight } NES_MISC_DATA_ENUM, *PNES_MISC_DATA_ENUM; */ typedef DWORD NES_MISC_DATA_ENUM; typedef struct _tagNES_MISC_DATA { CString sDescription; DWORD ptr; BYTE value; } NES_MISC_DATA, *PNES_MISC_DATA; class CMiscDataDlg: public CDialog { CFileLoader & m_File; CListView m_lv; CComboBox m_cb; NES_MISC_DATA_ENUM m_nmCurSel; static int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); int LVSort(NES_MISC_DATA_ENUM lv1, NES_MISC_DATA_ENUM lv2); std::map<NES_MISC_DATA_ENUM, NES_MISC_DATA> m_mData; VOID OnInit(LPARAM lParam); INT_PTR OnNotify(LPNMHDR lpnm); VOID OnCommand(USHORT uCmd, USHORT uId, HWND hCtl); VOID LoadItems(); VOID SaveItems(); INT PSOnApply(); public: CMiscDataDlg(HINSTANCE hInstance, CFileLoader & fl); };
loginsinex/smb2
smb2/h/GUI/Dialogs/cmainwnd.h
class CMainWnd: public CDialog { CFileLoader m_File; UINT m_uCurLevel; CLevelDlg dlvl; CLvlOptionsDlg dlvloptions; struct { CTreeView tv; CTabControl tc; CToolbar tb; } m_ctl; void OnCommand(USHORT uCmd, USHORT uId, HWND hCtl); void OnInit(LPARAM lParam); void OnButton(USHORT uId); void OnSize(UINT fwSizeType, SHORT cx, SHORT cy); void OnSizing(UINT fwSizeType, LPRECT lprc); INT_PTR OnNotify(LPNMHDR lpnm); void AlignPage(); void UpdatePages(); VOID ShowStat(); VOID ListLevels(); public: CMainWnd(HINSTANCE hInstance); UINT GetCurLevel(); VOID SetPage(INT iIndex); BOOL UnlockLevel(); BOOL UnlockEnemy(); void SelectLevel(USHORT uPtr, BYTE pos); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/ctoolbar.h
class CToolbar: public CControl { HIMAGELIST m_himl; BOOL AddCustomButton(int iBitmap, int idCommand, BYTE fState, BYTE fStyle, DWORD dwData, INT_PTR iString); BOOL AddCustomButton(int iBitmap, int idCommand, BYTE fState, BYTE fStyle, DWORD dwData, LPCTSTR iString); BOOL AddCustomButton(int iIndex, int iBitmap, int idCommand, BYTE fState, BYTE fStyle, DWORD dwData, INT_PTR iString); SIZE m_szButton; public: CToolbar(); ~CToolbar(); BOOL AdjustButtonsSize(); BOOL SetButtonsSize(USHORT cx, USHORT cy); HBITMAP SetImageList(HBITMAP hBitmap, COLORREF clrMask = 0); BOOL AddCheck(int iBitmap, int idCommand, LPCTSTR pszText = NULL, BOOL fChecked = FALSE, BOOL fEnabled = TRUE, LPARAM lParam = 0); BOOL AddRadio(int iBitmap, int idCommand, LPCTSTR pszText = NULL, BOOL fChecked = FALSE, BOOL fEnabled = TRUE, LPARAM lParam = 0); BOOL AddButton(int iBitmap, int idCommand, LPCTSTR pszText = NULL, BOOL fChecked = FALSE, BOOL fEnabled = TRUE, LPARAM lParam = 0); BOOL AddDropDownButton(int iBitmap, int idCommand, LPCTSTR pszText = NULL, BOOL fChecked = FALSE, BOOL fEnabled = TRUE, LPARAM lParam = 0); BOOL AddSeparator(); void EnableAll(BOOL fEnabled, ...); void CheckAll(BOOL fChecked, ...); BOOL Enabled(int idCommand); BOOL Checked(int idCommand); void Enabled(int idCommand, BOOL fEnable); void Checked(int idCommand, BOOL fCheck); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cpalette.h
class CPaletteDlg: public CDialog { CFileLoader & m_File; BOOL m_fAdditional; CComboBox m_cbWorld; CTrackBar m_tbPal; USHORT m_cbPal[16]; BYTE m_pPalette[16*8*7]; struct { HDC hDC; HDC hDCBuffer; HBITMAP hBmpBuffer; HBITMAP hOldBmp; HIMAGELIST hIml; } m_Buffer; VOID OnInit(LPARAM lParam); INT OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & fHandle); VOID OnCommand(USHORT uCmd, USHORT uId, HWND hCtl); INT PSOnApply(); VOID LoadItems(); VOID SaveItems(); VOID SetItems(); VOID WriteItems(); VOID MakeBuffer(); VOID ReleaseBuffer(); HIMAGELIST GetImage(); public: CPaletteDlg(HINSTANCE hInstance, CFileLoader & fl, BOOL fAdditional = FALSE); ~CPaletteDlg(); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cwarpsdlg.h
class CWarpsDlg: public CDialog { CFileLoader & m_File; CComboBox m_cbWarps[7]; VOID OnInit(LPARAM lParam); BYTE m_pData[7]; VOID LoadItems(); VOID SaveItems(); VOID WriteItems(); INT PSOnApply(); public: CWarpsDlg(HINSTANCE hInstance, CFileLoader & fl); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/cdwmapi.h
<filename>smb2/h/GUI/Wrapper/Controls/cdwmapi.h #include <dwmapi.h> #define DWM(Type) typedef HRESULT (WINAPI* Type) #define DWMCALL(Type, Func) if ( !m_hDwm ) \ return E_NOTIMPL; \ else \ return ((Type) GetProcAddress((HMODULE) m_hDwm, Func)) DWM(DWMDEFWINDOWPROC) (HWND, UINT, WPARAM, LPARAM, LRESULT*); DWM(DWMENABLEBLURBEHINDWINDOW) (HWND, const DWM_BLURBEHIND *); DWM(DWMENABLECOMPOSITION)(UINT); DWM(DWMEXTENDFRAMEINTOCLIENTAREA) (HWND, const MARGINS *); DWM(DWMGETCOLORIZATIONCOLOR) (DWORD*, BOOL*); DWM(DWMGETCOMPOSITIONTIMINGINFO) (HWND, DWM_TIMING_INFO*); DWM(DWMGETWINDOWATTRIBUTE) (HWND, DWORD, PVOID, DWORD); DWM(DWMISCOMPOSITIONENABLED) (BOOL*); DWM(DWMMODIFYPREVIOUSDXFRAMEDURATION) (HWND, INT, BOOL); DWM(DWMQUERYTHUMBNAILSOURCESIZE) (HTHUMBNAIL, PSIZE); DWM(DWMREGISTERTHUMBNAIL) (HWND, HWND*, PHTHUMBNAIL); DWM(DWMSETDXFRAMEDURATION) (HWND, INT); DWM(DWMSETPRESENTPARAMETERS) (HWND, DWM_PRESENT_PARAMETERS*); DWM(DWMSETWINDOWATTRIBUTE) (HWND, DWORD, LPCVOID, DWORD); DWM(DWMUNREGISTERTHUMBNAIL) (HTHUMBNAIL); DWM(DWMUPDATETHUMBNAILPROPERTIES) (HTHUMBNAIL, const DWM_THUMBNAIL_PROPERTIES*); class CDwmApi { HANDLE m_hDwm; public: CDwmApi(); HRESULT CDwmApi::DwmDefWindowProc(HWND, UINT, WPARAM, LPARAM, LRESULT*); HRESULT CDwmApi::DwmEnableBlurBehindWindow(HWND, const DWM_BLURBEHIND *); HRESULT CDwmApi::DwmEnableComposition(UINT); HRESULT CDwmApi::DwmExtendFrameIntoClientArea(HWND, const MARGINS *); HRESULT CDwmApi::DwmGetColorizationColor(DWORD*, BOOL*); HRESULT CDwmApi::DwmGetCompositionTimingInfo(HWND, DWM_TIMING_INFO*); HRESULT CDwmApi::DwmGetWindowAttribute(HWND, DWORD, PVOID, DWORD); HRESULT CDwmApi::DwmIsCompositionEnabled(BOOL*); HRESULT CDwmApi::DwmModifyPreviousDxFrameDuration(HWND, INT, BOOL); HRESULT CDwmApi::DwmQueryThumbNailSourceSize(HTHUMBNAIL, PSIZE); HRESULT CDwmApi::DwmRegisterThumbNail(HWND, HWND*, PHTHUMBNAIL); HRESULT CDwmApi::DwmSetDxFrameDuration(HWND, INT); HRESULT CDwmApi::DwmSetPresentParameters(HWND, DWM_PRESENT_PARAMETERS*); HRESULT CDwmApi::DwmSetWindowAttribute(HWND, DWORD, LPCVOID, DWORD); HRESULT CDwmApi::DwmUnregisterThumbnail(HTHUMBNAIL); HRESULT CDwmApi::DwmUpdateThumbnailProperties(HTHUMBNAIL, const DWM_THUMBNAIL_PROPERTIES*); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cbgtiles.h
class CBgTilesDlg: public CTilesDlg //public CDialog { BYTE m_pTilesArray[448]; VOID OnInit(LPARAM lParam); VOID SetTiles(INT i); VOID LoadItems(); VOID SaveItems(); VOID SetItems(); VOID WriteItems(); VOID OnButton(USHORT uId); INT_PTR OnNotify(LPNMHDR lpnm); VOID OnCommand(USHORT uCmd, USHORT uId, HWND hCtl); INT PSOnApply(); CComboBox m_cbWorld; CTrackBar m_tbBgType; USHORT m_cbTile[5]; DWORD m_uTbPos; //struct //{ // HIMAGELIST himl[5]; //} m_Image; public: CBgTilesDlg(HINSTANCE hInstance, CFileLoader & flLoader); ~CBgTilesDlg(); };
loginsinex/smb2
smb2/h/NES/cnestiles.h
<filename>smb2/h/NES/cnestiles.h #define TILES_WIDTH 0x10 #define TILES_HEIGHT 0x2000 #define TILE_WIDTH 0x08 #define TILE_HEIGHT 0x08 #define TILES_PTR 0x20010 #define TILE_COL0 0x00000000 #define TILE_COL1 0x000000FF #define TILE_COL2 0x0000FF00 #define TILE_COL3 0x00FF0000 typedef enum _tagNES_OBJECTS { noMushroom = 0 } NES_OBJECTS, *PNES_OBJECTS; class CNesTile { SIZE m_sz; POINT* m_pt; }; class CNesTiles { CBitmap m_bmTiles; public: CNesTiles(); BOOL LoadTiles(PBYTE ptr, DWORD uSize); BOOL MakeTile(CBitmap & bTile, DWORD uPtr, char cx, char cy); };
loginsinex/smb2
smb2/h/NES/cneseditor.h
typedef enum _tagNES_ITEM_TYPE { nitEnemy = 0, nitRegular = 1, nitGround = 2, nitEntrance = 3, nitPointer = 4 } NES_ITEM_TYPE, *PNES_ITEM_TYPE; class CFileLoader; class CNesItem; class CNesPage: public CNesItemsList<CNesItem> { DWORD m_nPage; public: VOID Page(DWORD i); DWORD Page(); BOOL InsertObject(CNesItem * pObj); BOOL SortObjects(); BOOL SortGroundsHorz(); BOOL SortGroundsVert(); CNesItem * Item(DWORD i); }; class CNesObjectsList: public CNesItemsList<NES_LEVEL_ITEM> { public: BOOL InsertObject(NES_LEVEL_ITEM * pItem); BOOL InsertSkipper(BOOL fDoubleSkipper); PNES_LEVEL_ITEM InsertNewObject(); PNES_LEVEL_ITEM Object(DWORD i); BOOL TrimSkippers(); ~CNesObjectsList(); }; class CNesLayer: public CNesItemsList<CNesPage> { BOOL m_fHorzLevel; DWORD m_nLayer; BOOL InsertPage(CNesPage * pPage); public: CNesLayer(BOOL fHorz) : m_fHorzLevel( fHorz ) { } ~CNesLayer(); BOOL SortObjects(); VOID Layer(DWORD i); DWORD Layer(); BOOL SetPagesCount(DWORD c); BOOL InsertObjectToPage(DWORD i, CNesItem * pObject); CNesPage* Page(DWORD i); }; class CNesLayerArray: public CNesItemsList<CNesLayer> { public: ~CNesLayerArray(); BOOL SetLayersCount(DWORD c, BOOL fHorz); CNesLayer * Layer(DWORD i); }; class CNesObjectsListsArray: public CNesItemsList<CNesObjectsList> { public: ~CNesObjectsListsArray(); BOOL SetListsCount(DWORD c); CNesObjectsList * ObjList(DWORD i); }; class CNesEditor: public CNesItemsList<CNesItem> { struct { BYTE fDirection:1; BYTE Reserved1:1; BYTE uColor:3; BYTE Reserved2:1; BYTE uEnemyColor:2; BYTE Reserved3:3; BYTE uGround:5; BYTE uLength:4; BYTE uObjectType:4; BYTE Reserved4:2; BYTE uTypeOfGround:3; BYTE Reserved5:1; BYTE uMusic:2; } m_levelFields; CNesItem *pInitialBg; CNesLevel & m_lvl; CNesEnemyData & m_enm; CFileLoader & m_file; CFileLoader * m_pFile; BOOL m_fChanged; struct { INT iWorld; INT iSubLevel; DWORD dwLevel; } m_Level; struct { DWORD dwPages; DWORD dwLayers; } m_Counters; struct { DWORD dwLevelLink; DWORD dwEnemyLink; } m_Links; BOOL CheckGroundCollision(UINT pos, INT iLayer, DWORD i = -1); BOOL AssembleHeader(); BOOL LoadLevel(CNesLevel & lvl, CNesEnemyData & enm, CFileLoader * file, DWORD dwCurLevel); BOOL MakeObjectsList(DWORD & lpdwCount, std::vector<NES_LEVEL_ITEM> & pItemsList, DWORD & lpdwHeader); BOOL MakeEnemiesList(DWORD & lpdwCount, std::vector<NES_LEVEL_ENEMY> & pItemsList); INT FetchCurWorld(); VOID Modified(); public: CNesEditor(CNesLevel & lvl, CNesEnemyData & enm, CFileLoader & file, DWORD dwCurLevel); ~CNesEditor(); BOOL RewritePoints(); DWORD CountPages(); DWORD CountLayers(); INT GetCurWorld(); INT GetSubLevel(); DWORD GetCurLevel(); BOOL UpdateCounters(); CNesItem LevelItem(UINT i); BYTE operator[](NES_LEVEL_FIELDS nlf); BOOL Apply(); BOOL CheckPagePointers(INT iPage); BOOL InsertObject(INT iLayer, UINT x, UINT y, BYTE regular_id); BOOL InsertEnemy(UINT x, UINT y, BYTE regular_id, BOOL fHidden); BOOL InsertGround(UINT pos, BYTE bGroundSet, BYTE bGroundType, INT iLayer); BOOL InsertPointer(INT iPage, BYTE param1, BYTE param2); BOOL MoveGround(UINT i, UINT pos); BOOL ChangeLayer(UINT i, INT iLayer); BOOL MoveObject(UINT i, UINT x, UINT y); BOOL DeleteObject(UINT i); BOOL MoveEnemy(UINT i, UINT x, UINT y, BOOL fHidden); BOOL InsertEntrance(INT iLayer, UINT x, UINT y, BYTE regular_id, BOOL fFarPointer, BYTE wParam, BYTE lParam); BOOL ChangeEntrancePointer(UINT i, BOOL fFarPointer, BYTE wParam, BYTE lParam); BOOL ChangePointer(UINT i, BYTE wParam, BYTE lParam); BOOL ChangeRegularSize(UINT i, BYTE wSize); BOOL ChangeGround(UINT i, BYTE bSet, BYTE bType); BOOL SetHeaderInfo(NES_LEVEL_FIELDS nlf, BYTE bNewValue); BOOL RemoveAll(); BOOL IsEnemyLayerLocked(); BOOL IsItemsLayerLocked(); DWORD ItemsLayerLink(); DWORD EnemiesLayerLink(); VOID SetItemsLayerLink(DWORD dwItemsLink); VOID SetEnemiesLayerLink(DWORD dwEnemiesLink); BOOL MakeJarLevel(); DWORD GetBgSet(BYTE bBgSet); BYTE GetBgTile(BYTE bBgSet, BYTE bBgType, INT iWorld = -1); BYTE GetObjTile(BYTE bObjectId); INT GetFX(INT iWorld = -1); BOOL GetColFromPalette(COLORREF *pColArray); NES_ITEM_DIM GetMasvDim(int item, NES_ITEM_DIM nid, USHORT & type); NES_ITEM_DIM GetVertDim(int item, NES_ITEM_DIM nid, USHORT & type); NES_ITEM_DIM GetSingDim(int item, NES_ITEM_DIM nid, USHORT & type); NES_ITEM_DIM GetHorzDim(int item, NES_ITEM_DIM nid, USHORT & type); NES_ITEM_DIM GetEntrDim(int item, NES_ITEM_DIM nid, USHORT & type); BOOL GetLocalLevelItems(std::vector<NES_LEVEL_ITEM> & vItems); BOOL GetCurrentLevelItems(std::vector<NES_LEVEL_ITEM> & vItems); BOOL GetLocalEnemyItems(std::vector<NES_LEVEL_ENEMY> & vItems); BOOL GetCurrentEnemyItems(std::vector<NES_LEVEL_ENEMY> & vItems); BOOL Changed(); }; class CNesItem { NES_ITEM_TYPE m_type; POINT m_pt; SIZE m_sz; INT m_iLayer; INT m_iPage; union { BYTE pData[4]; struct { BYTE id; BYTE uItemPtr[3]; } Regular; struct { BYTE uSets; BYTE uType; BYTE Reserved[2]; } Ground; struct { BYTE uEntranceId; BYTE uEntranceParameter[3]; } Entrance; struct { BYTE id; BYTE Reserved[3]; } General; struct { USHORT uPtrData; BYTE Reserved[2]; } Pointer; struct { BYTE id; BYTE Reserved[3]; } Enemy; } m_obj; BOOL SetLayer(INT iLayer); BOOL SetPosition(UINT x, UINT y); BOOL SetPage(INT iPage); BOOL SetEntranceParam(BOOL fFarPointer, BYTE wParam, BYTE lParam); BOOL SetPtr(BYTE wParam, BYTE lParam); public: CNesItem(PNES_LEVEL_ITEM lvl, POINT & pt, INT iLayer, INT iPage); // regular or entrance CNesItem(PNES_LEVEL_ENEMY enm, POINT & pt, INT iPage); // enemy CNesItem(PNES_LEVEL_ITEM lvl, POINT & pt, INT iLayer, INT iPage, BYTE bgType); // ground CNesItem(PNES_LEVEL_ITEM lvl, INT iPage); // pointer BOOL ChangeBgType(BYTE bgType); // friend BOOL CNesEditor::LoadLevel(CNesLevel & lvl, CNesEnemyData & enm, CFileLoader * file, DWORD dwCurLevel); friend BOOL CNesEditor::ChangeLayer(UINT i, INT iLayer); friend BOOL CNesEditor::MoveObject(UINT i, UINT x, UINT y); friend BOOL CNesEditor::MoveEnemy(UINT i, UINT x, UINT y, BOOL fHidden); friend BOOL CNesEditor::MoveGround(UINT i, UINT pos); friend BOOL CNesEditor::DeleteObject(UINT i); friend BOOL CNesEditor::ChangeEntrancePointer(UINT i, BOOL fFarPointer, BYTE wParam, BYTE lParam); friend BOOL CNesEditor::ChangePointer(UINT i, BYTE wParam, BYTE lParam); friend BOOL CNesEditor::SetHeaderInfo(NES_LEVEL_FIELDS nlf, BYTE bNewValue); friend BOOL CNesEditor::RewritePoints(); friend BOOL CNesEditor::ChangeRegularSize(UINT i, BYTE wSize); friend BOOL CNesEditor::ChangeGround(UINT i, BYTE bSet, BYTE bType); NES_ITEM_TYPE Type(); USHORT Ground(); BYTE Regular(); BYTE RegularId(); BYTE Enemy(); POINT Pos(); USHORT Pointer(); INT Page(); INT Layer(); BYTE EntranceParameter(INT i); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/ctreeview.h
class CTreeView: public CControl { BOOL ReqItem(HTREEITEM hItem, LPTV_ITEM lptvi); BOOL UpdItem(HTREEITEM hItem, LPTV_ITEM lptvi); public: HTREEITEM AddItem(HTREEITEM hParentItem, LPCTSTR lpszText, LPARAM lParam, BOOL bBold = FALSE, BOOL bSelected = FALSE, BOOL bExpanded = FALSE, HTREEITEM hInsertAfter = TVI_LAST); HTREEITEM GetItem(DWORD dwFlag, HTREEITEM hFrom = NULL); HTREEITEM GetCurSel(); void SetCurSel(HTREEITEM hItem); void Param(HTREEITEM hItem, LPARAM lParam); LPARAM Param(HTREEITEM hItem); void Text(HTREEITEM hItem, LPCTSTR lpszText); CString Text(HTREEITEM hItem); void State(HTREEITEM hItem, DWORD dwState); DWORD State(HTREEITEM hItem); void CheckItem(HTREEITEM hTree, BOOL bCheck); BOOL CheckItem(HTREEITEM hTree); void ResetContent(); };
loginsinex/smb2
smb2/h/GUI/Dialogs/clvldraw.h
#define ZLVLDRAW_CLASS TEXT("SysLevelDraw32") #define MAX_TPL 20 #define LDN_HITEST -1201 #define LDN_HITESTENEMY -1202 #define LDN_DELETE -1203 #define LDN_INSERT -1204 #define LDN_EDIT -1205 #define LDN_BGLIST -1206 #define LDN_PTRLIST -1207 #define LDN_LEVELDATA -1208 #define LDN_CHANGELAYER -1209 #define LDN_CHANGEBG -1210 #define LDN_NEXTITEM -1211 #define LDN_JUMPTOPOINTER -1212 #define LDN_ITEMSELECTED -1213 #define LDN_INSERTJARENEMY -1214 #define LDN_MAKEJAR -1215 #define CONVERT_REGULAR(r) ((r) >= 0x30 ? ( 0x30 + ((r)-0x30)/0x10 ) : (r)) #define BG_PRIOR(regular, bitset, fx, grtype, horz) \ ( !g_mPriorityList[(regular)].bgPriority ? \ 0 : \ ( \ (horz) ? \ g_mbgPriority[8*(fx)+(grtype)].gr.gr[(bitset)] : \ g_mvbgPriority[8*(fx)+(grtype)].gr.gr[(bitset)] \ ) \ ) void InitLevelDraw(); typedef struct _tagNMLVLDRWHT { NMHDR nm; POINT pos; USHORT iItem; } NMLVLDRWHT, *PNMLVLDRWHT; typedef struct _tagNES_GITEM { union { UINT idItem; struct { USHORT id; USHORT type; } Item; } Item; UINT idTile; BOOL fVisible; BOOL fHidden; } NES_GITEM, *PNES_GITEM; class CLvlDraw: public CNesItemsList<NES_LEVEL_ITEM> { CFont m_Font; HWND m_hWnd; HWND m_hParentWnd; HFONT m_hGlobalFont; struct { CBitmap bmBuffer; CBitmap bmLevel; CBitmap bmSpecial; CBitmap bmTpl[MAX_TPL]; CBitmap bmGamma; CBitmap bmGammaTpl; CBitmap bmGrGammaTpl; } m_Bmp; struct { HCURSOR hArrow; HCURSOR hMove; HCURSOR hCurrent; } m_cursor; CNesEditor * m_pvEditor; PNES_ITEM_DIM m_vDim; SIZE m_dcsz; SIZE m_sz[MAX_TPL]; UINT m_uGammaIndex; COLORREF m_crBg; HDC m_hDC; struct { INT fx; BYTE eColor; SIZE sz; PNES_GITEM pItems; PNES_GITEM pEnemyItems; SIZE szSpecial; PNES_GITEM pSpecial; BOOL fDisableEditor; std::vector<BOOL> vHilite; } m_Canvas; struct { SIZE sz; UINT scrollX; UINT scrollY; BOOL fVertical; BOOL fHorizontal; } m_scroll; struct { BOOL fObjectCatched; BOOL fCatchEnemies; BOOL fCatchJarEnemies; POINT ptDelta; DWORD dwCatchedObject; } m_Catch; static LRESULT CALLBACK ControlProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); VOID OnErase(HDC hDC); VOID OnKeyDown(UINT vKey, USHORT uScanCode); VOID OnMouseMove(UINT uCtl, SHORT x, SHORT y); VOID OnMouseDown(UINT uCtl, SHORT x, SHORT y); VOID OnMouseUp(UINT uCtl, SHORT x, SHORT y); VOID OnContextMenu(); VOID OnResize(); VOID OnDeleteItem(); VOID OnChangeBg(int code); void OnNextItem(BOOL fPrevious); INT_PTR DoNotify(UINT uCode, DWORD i, UINT x, UINT y); VOID SetScroll(); VOID UpdateScroll(UINT uScrollType, USHORT uPos, USHORT uReq); CLvlDraw(LPCREATESTRUCT lpcs, HWND hWnd); ~CLvlDraw(); VOID AllocCanvas(UINT cx, UINT cy, INT fx); BOOL SetCanvasEnemyItem(PNES_GITEM pItem, UINT x, UINT y, BOOL fHiddenEnemy = FALSE); BOOL EraseEnemyCanvas(); BOOL EraseItemsCanvas(); BOOL GetCanvasEnemyItem(PNES_GITEM pItem, UINT x, UINT y); VOID DestroyCanvas(); BOOL SetCanvasItem(PNES_GITEM pItem, UINT x, UINT y); BOOL SetCanvasNullItem(UINT x, UINT y); BOOL IsCanvasItemUsed(UINT x, UINT y); BOOL IsCanvasLineContainLayerLimit(UINT x, UINT y, UINT cx, INT iLayer); BOOL GetCanvasItem(UINT x, UINT y, PNES_GITEM nItem); BOOL SetSpecialCanvasItem(UINT x, UINT y, PNES_GITEM nItem); BOOL GetSpecialCanvasItem(UINT x, UINT y, PNES_GITEM nItem); BOOL DrawCanvas(); BOOL DrawSpecialCanvas(); VOID RedrawBuffer(BOOL fSetScroll = TRUE); BOOL RedrawLevel(BOOL fEraseEnemies = FALSE); VOID UseGamma(UINT gammaIndex, UINT tplIndex, UINT tplGrIndex); VOID InitSize(COLORREF clr, UINT cx, UINT cy, UINT pixX, UINT pixY); VOID Draw(UINT index, UINT x, UINT y, UINT cx, UINT cy, UINT dx, UINT dy, BOOL fSelected = FALSE); VOID DrawGamma(UINT gammaIndex, UINT index, UINT x, UINT y, UINT cx, UINT cy, UINT dx, UINT dy, BOOL fSelected = FALSE, BOOL fHilited = FALSE); VOID DrawGrGamma(BYTE index, UINT x, UINT y, BOOL fSelected = FALSE, BOOL fHilited = FALSE); VOID DrawSpecialGamma(UINT gammaIndex, UINT index, UINT x, UINT y, UINT cx, UINT cy, UINT dx, UINT dy, BOOL fSelected = FALSE); BOOL DrawObjectEx(USHORT item, USHORT fx, USHORT uObjectType, CNesItem & x); BOOL DrawSingleObjectEx(USHORT item, USHORT fx, CNesItem & x); BOOL DrawHorzObjectEx(USHORT item, USHORT fx, CNesItem & x); BOOL DrawVertObjectEx(USHORT item, USHORT fx, CNesItem & x, BOOL fLimitByLayer = FALSE, BOOL fDirection = FALSE); // fDirection: TRUE - to top, FALSE - to down BOOL DrawHorzGrObjectEx(USHORT item, CNesItem & x); BOOL DrawVertGrObjectEx(USHORT item, CNesItem & x, BOOL fLimitByLayer = FALSE); BOOL DrawMasvObjectEx(USHORT item, USHORT fx, CNesItem & x, BOOL fLimitByLayer = FALSE); BOOL DrawSpecialObjectEx(USHORT item, USHORT fx, CNesItem & x); BOOL DrawGroundEx(USHORT item, USHORT fx, CNesItem & x); BOOL DrawPyramidEx(USHORT item, USHORT fx, CNesItem & x); BOOL DrawDesertEntrance(USHORT item, USHORT fx, CNesItem & x); BOOL DrawRedBg(USHORT item, USHORT fx, CNesItem & x); BOOL DrawStarBg(USHORT item, USHORT fx, CNesItem & x); friend void InitLevelDraw(); public: VOID LoadBmp(HINSTANCE hInstance, LPTSTR pszResource, UINT index, UINT cx, UINT cy); VOID LoadGamma(HINSTANCE hInstance, LPTSTR pszResource); VOID UseEnemyMask(UINT indexOfMask, UINT indexOfEnemy); BOOL DrawLevelEx(DWORD dwCurLevel, CNesEditor * ed); BOOL SetCatchCanvas(BOOL fEnemiesCanvas, BOOL fJarEnemies); void SetCursorMode(BOOL fMove); VOID SelectPos(int page, BYTE pos); UINT GetSelectedItem(); VOID RequestRedraw(BOOL fWithEnemies = FALSE); };
loginsinex/smb2
smb2/h/GUI/Dialogs/Advanced/cbgsetdlg.h
<reponame>loginsinex/smb2 class CBgSetHorzDlg: public CTilesDlg { CListView m_lvTiles; CTrackBar m_tbSet; CComboBox m_cbWorld; DWORD m_dwBgSet[32]; DWORD m_tbPos; BOOL m_fHorizontal; VOID SetTiles(INT iWorld); VOID OnInit(LPARAM lParam); INT_PTR OnNotify(LPNMHDR lpnm); VOID OnCommand(USHORT uCmd, USHORT uId, HWND hWnd); INT PSOnApply(); VOID LoadItems(); VOID SaveItems(); VOID SetItems(); VOID WriteItems(); public: CBgSetHorzDlg(HINSTANCE hInstance, CFileLoader & fl, BOOL fHorizontal); };
loginsinex/smb2
smb2/h/GUI/Wrapper/cpropsheet.h
<gh_stars>1-10 class CPropSheet { HINSTANCE m_hInstance; HWND m_hWnd; // this field will set by CDialog::PropSheetDialogProc !!! BOOL m_fCreated; BOOL m_fSetToClose; vector<PROPSHEETPAGE> m_vPSList; DWORD m_dwFlags; CDialog * m_pParent; void SetFlag(DWORD dwFlag, BOOL fSet); INT_PTR pSendMessage(UINT uMsg, WPARAM wParam = 0, LPARAM lParam = 0); CDialog * WindowToDialog(HWND hWnd); HWND DialogToWindow(CDialog * pDialog); friend INT_PTR CALLBACK CDialog::PropSheetDialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); public: CPropSheet(HINSTANCE hInstance); ~CPropSheet(); BOOL AddSheet(CDialog * pDialog, LPARAM lParam = 0, LPTSTR pszTitle = NULL, BOOL fForceCreate = FALSE); INT_PTR Show(CDialog * pParent, LPARAM lParam = 0, LPTSTR pszCaption = NULL, DWORD dwFirstPage = 0); CDialog * GetParent(); HWND GetWindowHandle(); VOID FApply(BOOL fApply); VOID FAppendTitle(BOOL fAppendTitle); VOID EChanged(BOOL fChanged, CDialog * pCallee); VOID ESetClose(); BOOL EGetClose(); HWND ETabCtl(); VOID EDoCommand(UINT uButton); VOID ENeedReboot(); VOID ENeedRestart(); VOID ETitle(LPTSTR lpszTitle, BOOL fPropertiesForFlag = FALSE); CDialog * EGetPage(INT iIndex); INT EGetIndex(CDialog * pDialog); CDialog * EGetCurrentPage(); INT EGetCurrentIndex(); VOID ESetCurrentPage(INT iIndex); VOID ESetCurrentPage(CDialog * pDialog); };
loginsinex/smb2
smb2/h/NES/cnesleveldata.h
extern const LPTSTR g_szItemName[]; extern const LPTSTR g_szSOName[]; #define NES_JAR_HEADER 0x18E30101 #define IS_POINTABLE(obj) ( nliEntrance == (obj)->nli || nliRegular == (obj)->nli ) #define IS_MVPOINT(obj) ( nliSkipper == (obj)->nli || nliBackToStart == (obj)->nli ) #define OBJ_SUM(obj1, obj2) ( (obj2)->Object.General.y += (obj1)->Object.General.y ) #define OBJ_SUB(obj1, obj2) ( (obj2)->Object.General.y -= (obj1)->Object.General.y ) #define OBJ_RST(obj1) ( (obj1)->Object.General.y = 0 ) #define OBJ_EQ(obj1, obj2) ( (obj2)->Object.General.y = (obj1)->Object.General.y ) #define IS_OBJ_LESS(obj1, obj2) ( (obj1)->Object.General.y < (obj2)->Object.General.y ) #define IS_OBJ_GREAT(obj1, obj2) ( (obj1)->Object.General.y > (obj2)->Object.General.y ) #define IS_OBJ_EQ(obj1, obj2) ( (obj1)->Object.General.y == (obj2)->Object.General.y ) typedef enum { nliSkipper = 0, // 1 byte nliBackToStart = 1, // 1 byte nliRegular = 2, // 2 bytes nliGroundSet = 3, // 2 bytes nliGroundType = 4, // 2 bytes nliPtr = 5, // 3 bytes nliEntrance = 6, // 4 bytes nliUnknown = 7 // 2 bytes? } NLI_TYPE, *PNLI_TYPE; typedef enum _tagNES_LEVEL_FIELDS { nlfDirection = 0, nlfReserved1 = 1, nlfColor = 2, nlfReserved2 = 3, nlfEnemyColor = 4, nlfReserved3 = 5, nlfGround = 6, nlfLength = 7, nlfObjectType = 8, nlfReserved4 = 9, nlfTypeOfGround = 10, nlfReserved5 = 11, nlfMusic = 12 } NES_LEVEL_FIELDS; typedef struct _tagNES_LEVEL_ITEM { NLI_TYPE nli; POINT pt; DWORD Page; union { BYTE pData[5]; struct { BYTE uType; BYTE Reserved2[4]; } Skipper; struct { BYTE Reserved[5]; } BackToStart; struct { BYTE x:4; BYTE y:4; BYTE id; BYTE Reserved[2]; } Regular; struct { BYTE Reserved; BYTE uSets; BYTE Reserved2[3]; } GroundSet; struct { BYTE Reserved; BYTE uType; BYTE Reserved2[3]; } GroundType; struct { BYTE Reserved; BYTE uParameter[2]; BYTE Reserved2[2]; } Pointer; struct { BYTE y:4; BYTE x:4; BYTE uEntranceId; BYTE uEntranceParameter[3]; } Entrance; struct { BYTE x:4; BYTE y:4; BYTE id; BYTE Reserved[3]; } General; struct { BYTE Reserved[5]; } Unknown; } Object; DWORD SizeOfItem(); } NES_LEVEL_ITEM, *PNES_LEVEL_ITEM; class CNesLevelContainer: public CNesItemsList<NES_LEVEL_ITEM> { DWORD m_dwLevelHeader; DWORD m_dwLinkedToLevel; DWORD m_dwLevelPtr; DWORD m_dwLevelSize; struct { BYTE fDirection:1; BYTE Reserved1:1; BYTE uColor:3; BYTE Reserved2:1; BYTE uEnemyColor:2; BYTE Reserved3:3; BYTE uGround:5; BYTE uLength:4; BYTE uObjectType:4; BYTE Reserved4:2; BYTE uTypeOfGround:3; BYTE Reserved5:1; BYTE uMusic:2; } m_levelFields; VOID FlushObjects(); BOOL RereadPoints(); VOID StoreSizeOfLevel(); VOID StoreHeader(); public: CNesLevelContainer(); ~CNesLevelContainer(); VOID SetLevelPtr(DWORD ptr); DWORD GetLevelPtr(); BYTE operator[](NES_LEVEL_FIELDS index); VOID LoadLevel(PBYTE ptr, DWORD dwLinkedTo = -1); VOID LoadLevelData(DWORD dwLevelHeader, std::vector<NES_LEVEL_ITEM> & pItemsList, DWORD dwCount); DWORD SizeOfLevel(); DWORD TotalPages(); BOOL MakeByteArray(PBYTE * pArray, LPDWORD lpdwCount); BOOL IsLinkedLevel(); DWORD LinkLevel(); const NES_LEVEL_ITEM LevelData(UINT itemIndex); DWORD LevelHeader(); DWORD AddRef(); DWORD Release(); BOOL MakeJarLevel(); }; class CNesLevel: public CNesLevelContainer { };
loginsinex/smb2
smb2/h/GUI/Dialogs/Editor/cchglayerdlg.h
class CChgLayerDlg: public CDialog { struct { INT iLayer; INT iMaxLayer; } m_LayerCounter; VOID OnInit(LPARAM lParam); VOID OnOK(); VOID OnCancel(); public: CChgLayerDlg(HINSTANCE hInstance, INT iCurrentLayer, INT iMaximumLayer); INT GetLayerSelection(); };
loginsinex/smb2
smb2/h/GUI/Wrapper/csizeanchor.h
#define ANCHOR_LEFT_TOP 0 #define ANCHOR_LEFT_BOTTOM 1 #define ANCHOR_RIGHT_TOP 2 #define ANCHOR_RIGHT_BOTTOM 3 #define ANCHOR_LEFT 4 #define ANCHOR_RIGHT 5 #define ANCHOR_TOP 6 #define ANCHOR_BOTTOM 7 #define ANCHOR_FULL 8 typedef enum { AnchorNull, AnchorHardLinkLeftTop, AnchorHardLinkRightBottom, AnchorSoftLink } AnchorType; typedef struct _tagANCHOR_CORNER { AnchorType type; union { struct { UINT topleft, bottomright; } hard; struct { UINT up, down; } soft; } corner; } ANCHOR_CORNER, *LPANCHOR_CORNER; typedef struct _tagANCHOR_DATA { ANCHOR_CORNER left; ANCHOR_CORNER top; ANCHOR_CORNER right; ANCHOR_CORNER bottom; } ANCHOR_DATA, *LPANCHOR_DATA; class CSizeAnchor { HWND m_hParent; UINT m_uId; ANCHOR_DATA m_ad; VOID InternalResize(LPRECT lprc); public: CSizeAnchor(UINT uId, AnchorType left = AnchorNull, AnchorType top = AnchorNull, AnchorType right = AnchorNull, AnchorType bottom = AnchorNull); VOID Initialize(HWND hParent); VOID ResizeByDefer(HDWP hDwp); USHORT ControlId(); };
loginsinex/smb2
smb2/h/GUI/Wrapper/Controls/ccombobox.h
class CComboBox: public CControl { public: INT AddString(LPCTSTR lpszString, LPARAM lParam = 0); INT GetCurSel(); void SetCurSel(INT iIndex); LPARAM GetParam(INT iIndex); };
hwengmgr/panasonic-sensor
embedded-uart-common/sample-implementations/linux/sensirion_uart_implementation.c
<filename>embedded-uart-common/sample-implementations/linux/sensirion_uart_implementation.c /* * Copyright (c) 2018, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sensirion_arch_config.h" #include "sensirion_uart.h" #include <fcntl.h> #include <stdio.h> #include <termios.h> #include <unistd.h> // Adapted from // http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart //#define TTYDEV "/dev/ttyUSB0" #define TTYDEV "/dev/serial0" static int uart_fd = -1; /** * sensirion_uart_select_port() - select the UART port index to use * THE IMPLEMENTATION IS OPTIONAL ON SINGLE-PORT * SETUPS (only one SPS30) * * Return: 0 on success, an error code otherwise */ int16_t sensirion_uart_select_port(uint8_t port) { return 0; } int16_t sensirion_uart_open() { // The flags (defined in fcntl.h): // Access modes (use 1 of these): // O_RDONLY - Open for reading only. // O_RDWR - Open for reading and writing. // O_WRONLY - Open for writing only. // O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. // When set read requests on the file can return immediately with a // failure status if there is no input immediately available (instead // of blocking). Likewise, write requests can also return immediately // with a failure status if the output can't be written immediately. // O_NOCTTY - When set and path identifies a terminal device, open() // shall not cause the terminal device to become the controlling // terminal for the process. uart_fd = open(TTYDEV, O_RDWR | O_NOCTTY); if (uart_fd == -1) { fprintf(stderr, "Error opening UART. Ensure it's not otherwise used\n"); return -1; } // see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html: // CSIZE:- CS5, CS6, CS7, CS8 // CLOCAL - Ignore modem status lines // CREAD - Enable receiver // IGNPAR = Ignore characters with parity errors // ICRNL - Map CR to NL on input (Use for ASCII comms where you want to // auto correct end of line characters, // don't use for bianry comms) // PARENB - Parity enable // PARODD - Odd parity (else even) struct termios options; tcgetattr(uart_fd, &options); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; // set baud rate options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag = 0; //set timeout on read options.c_cc[VTIME] = 100; //1sec options.c_cc[VMIN] = 0; tcflush(uart_fd, TCIFLUSH); tcsetattr(uart_fd, TCSANOW, &options); return 0; } int16_t sensirion_uart_release() { return close(uart_fd); } int16_t sensirion_uart_tx(uint16_t data_len, const uint8_t *data) { if (uart_fd == -1) return -1; return write(uart_fd, (void *)data, data_len); } int16_t sensirion_uart_rx(uint16_t max_data_len, uint8_t *data) { if (uart_fd == -1) return -1; return read(uart_fd, (void *)data, max_data_len); } void sensirion_sleep_usec(uint32_t useconds) { usleep(useconds); }
mikaelhu0823/ThreadPool
libThreadPool/libThreadPool/ThreadPool.h
#pragma once #include <list> #include <thread> #include <functional> #include <memory> #include <atomic> #include "SyncTaskQueue.h" namespace Thread { constexpr int16_t MaxTaskCount = 100; class ThreadPool { public: using Task = std::function<void()>; explicit ThreadPool() : taskQueue_(MaxTaskCount) { } ~ThreadPool() { Stop(); } void Start(int num_threads = std::thread::hardware_concurrency()) { bExit_ = false; for (int i = 0; i < num_threads; ++i) { threadGroup_.emplace_back(std::make_shared<std::thread>([this]() { while (!bExit_) { std::list<Task> list; taskQueue_.Take(list); for (auto& task : list) { if (bExit_) return; task(); } } })); } } void Stop() { std::call_once(flag_, [this] { StopThreadGroup(); }); } void AddTask(Task&& t) { taskQueue_.Put(std::forward<Task>(t)); } void AddTask(const Task& t) { taskQueue_.Put(t); } protected: void StopThreadGroup() { taskQueue_.Stop(); bExit_ = true; for (auto thread : threadGroup_) { if (thread && thread->joinable()) thread->join(); } threadGroup_.clear(); } protected: std::list<std::shared_ptr<std::thread>> threadGroup_; SyncTaskQueue<Task> taskQueue_; std::atomic_bool bExit_{ false }; std::once_flag flag_; }; }
MeshGeometry/codecolor
Source/CodeColorer.h
#include "Core/Context.h" #include "Core/Object.h" #include "Container/Vector.h" #include "Container/Str.h" #include "Core/Variant.h" #include "IO/Deserializer.h" #include "IO/File.h" #include "IO/FileSystem.h" using namespace Urho3D; struct ColorRule { String name_; String regex_; Color color_; ColorRule::ColorRule() {}; ColorRule::ColorRule(String name, String regex, Color col) : name_(name), regex_(regex), color_(col) { } }; URHO3D_API class CodeColorer : public Object { URHO3D_OBJECT(CodeColorer, Object); public: CodeColorer(Context* context); ~CodeColorer() {}; //the main functions PODVector<char> CreateColors(String& code); PODVector<char> CreateColors(PODVector<char>& code); bool CreateColors(String path, PODVector<char>& code, PODVector<char>& styles); //some helpers bool GetRulesFromFile(String path); void ApplyColorRule(ColorRule rule, const PODVector<char>& rawCode, PODVector<char>& styleMap); protected: Vector<ColorRule> colorRules_; };
vernez/pngquant
rwpng.h
/*--------------------------------------------------------------------------- pngquant: RGBA -> RGBA-palette quantization program rwpng.h --------------------------------------------------------------------------- © 1998-2000 by <NAME>. © 2009-2014 by <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ #ifndef RWPNG_H #define RWPNG_H #include "png.h" /* if this include fails, you need to install libpng (e.g. libpng-devel package) */ #include <setjmp.h> #ifndef USE_COCOA #define USE_COCOA 0 #endif typedef enum { SUCCESS = 0, MISSING_ARGUMENT = 1, READ_ERROR = 2, INVALID_ARGUMENT = 4, NOT_OVERWRITING_ERROR = 15, CANT_WRITE_ERROR = 16, OUT_OF_MEMORY_ERROR = 17, WRONG_ARCHITECTURE = 18, // Missing SSE PNG_OUT_OF_MEMORY_ERROR = 24, LIBPNG_FATAL_ERROR = 25, LIBPNG_INIT_ERROR = 35, TOO_LARGE_FILE = 98, TOO_LOW_QUALITY = 99, } pngquant_error; struct rwpng_chunk { struct rwpng_chunk *next; png_byte *data; png_size_t size; png_byte name[5]; png_byte location; }; #if USE_LCMS typedef enum { NONE = 0, ICCP = 1, // used ICC profile ICCP_WARN_GRAY = 2, // ignore and warn about GRAY ICC profile GAMA_CHRM = 3, // used gAMA and cHARM } lcms_transform; #endif typedef struct { jmp_buf jmpbuf; png_uint_32 width; png_uint_32 height; png_size_t file_size; double gamma; unsigned char **row_pointers; unsigned char *rgba_data; struct rwpng_chunk *chunks; #if USE_LCMS lcms_transform lcms_status; #endif } png24_image; typedef struct { jmp_buf jmpbuf; png_uint_32 width; png_uint_32 height; png_size_t maximum_file_size; double gamma; unsigned char **row_pointers; unsigned char *indexed_data; unsigned int num_palette; unsigned int num_trans; png_color palette[256]; unsigned char trans[256]; struct rwpng_chunk *chunks; char fast_compression; } png8_image; typedef union { jmp_buf jmpbuf; png24_image png24; png8_image png8; } rwpng_png_image; /* prototypes for public functions in rwpng.c */ void rwpng_version_info(FILE *fp); pngquant_error rwpng_read_image24(FILE *infile, png24_image *mainprog_ptr, int verbose); pngquant_error rwpng_write_image8(FILE *outfile, const png8_image *mainprog_ptr); pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr); void rwpng_free_image24(png24_image *); void rwpng_free_image8(png8_image *); #endif
glustful/PDFReader
PDFReader/PDFReaderSlideController.h
<filename>PDFReader/PDFReaderSlideController.h // // PDFReaderSlideController.h // PDFReader // // Created by atide on 16/6/7. // Copyright © 2016年 atide. All rights reserved. // #import <UIKit/UIKit.h> @interface PDFReaderSlideController : UIViewController <UIScrollViewDelegate>{ UIScrollView *_scrollView; UIScrollView *_prevPageView; UIScrollView *_currentPageView; UIScrollView *_nextPageView; NSInteger _currentPageIndex; CGFloat offset; } @property float scale_; -(CGRect)zoomRectForScale:(float)scale inView:(UIScrollView*)scrollView withCenter:(CGPoint)center; -(void) skip: (NSInteger) num; @property (weak, nonatomic) IBOutlet UIView *pdfView; @end
Viladoman/StructLayout
Parsers/PDBLayout/src/CommandLine.h
<reponame>Viladoman/StructLayout #pragma once struct ExportParams { ExportParams(); const wchar_t* input; const wchar_t* output; const wchar_t* locationFile; unsigned int locationLine; }; namespace CommandLine { int Parse(ExportParams& args, int argc, wchar_t* argv[]); }
Viladoman/StructLayout
Parsers/Shared/IO.h
<gh_stars>100-1000 #pragma once #define LOG_ALWAYS(...) { IO::Log(IO::Verbosity::Always,__VA_ARGS__); IO::Log(IO::Verbosity::Always,"\n");} #define LOG_ERROR(...) { IO::Log(IO::Verbosity::Always,"[ERROR] "##__VA_ARGS__); IO::Log(IO::Verbosity::Always,"\n");} #define LOG_WARNING(...) { IO::Log(IO::Verbosity::Always,"[WARNING] "##__VA_ARGS__); IO::Log(IO::Verbosity::Always,"\n");} #define LOG_PROGRESS(...) { IO::Log(IO::Verbosity::Progress,__VA_ARGS__); IO::Log(IO::Verbosity::Progress,"\n");} #define LOG_INFO(...) { IO::Log(IO::Verbosity::Info,__VA_ARGS__); IO::Log(IO::Verbosity::Info,"\n");} namespace Layout { struct Result; } namespace IO { ////////////////////////////////////////////////////////////////////////////////////////// // Logging enum class Verbosity { Always, Progress, Info, Invalid }; void SetVerbosityLevel(const Verbosity level); void Log(const Verbosity level, const char* format, ...); void LogTime(const Verbosity level, const char* prefix, long miliseconds); ////////////////////////////////////////////////////////////////////////////////////////// // Export bool ToFile(const Layout::Result& result, const char* filename); }
Viladoman/StructLayout
Parsers/ClangLayout/src/Parser.h
#pragma once namespace Parser { bool Parse(int argc, const char* argv[]); }
Viladoman/StructLayout
Parsers/PDBLayout/src/PDBReader.h
#pragma once namespace PDBReader { bool ExportAtLocation(const wchar_t* pdbFile, const wchar_t* filename, const int line, const wchar_t* output); }
Viladoman/StructLayout
TestProjects/Regular/Folder Space/TestHeader.h
<filename>TestProjects/Regular/Folder Space/TestHeader.h #pragma once namespace Test { struct Base { bool maybe; double bigNumber; }; }
Viladoman/StructLayout
Parsers/Shared/LayoutDefinitions.h
<gh_stars>100-1000 #pragma once #include <vector> #include <string> namespace Layout { // ---------------------------------------------------------------------------------------------------------- using TAmount = long long; using TFiles = std::vector<std::string>; enum { INVALID_FILE_INDEX = -1 }; // ---------------------------------------------------------------------------------------------------------- enum class Category : unsigned char { Root = 0, SimpleField, Bitfield, ComplexField, VPrimaryBase, VBase, NVPrimaryBase, NVBase, VTablePtr, VFTablePtr, VBTablePtr, VtorDisp, }; // ---------------------------------------------------------------------------------------------------------- struct Location { Location() : fileIndex(INVALID_FILE_INDEX) , line(0u) , column(0u) {} int fileIndex; unsigned int line; unsigned int column; }; // ---------------------------------------------------------------------------------------------------------- struct Node { Node() : nature(Category::Root) , offset(0u) , size(1u) , align(1u) {} std::string name; std::string type; std::vector<Node*> children; TAmount offset; TAmount size; TAmount align; Location typeLocation; Location fieldLocation; Category nature; }; // ---------------------------------------------------------------------------------------------------------- struct Result { Result() : node(nullptr) {} Node* node; TFiles files; }; }
Almeswe/network
client/src/client.h
<gh_stars>0 #pragma once #pragma warning(disable : 4996) #include "server.h" #define EmptyIP "" #define EmptyPort -1 namespace Network { class Client { private: int bufSize; int port = EmptyPort; int clientAddrSize; WSADATA wsa; SOCKET clientSocket; sockaddr_in clientAddr; char buffer[TcpPackSize]; std::string ip = EmptyIP; public: Client(); ~Client(); private: int Init(); public: void Connect(int port, std::string ip); void Disconnect(); private: int ReceiveData(); int SendDataTo(); int ProcessData(); void ExchangeData(); }; }
Almeswe/network
server/src/conslog.h
<filename>server/src/conslog.h #pragma once #pragma warning(disable:4996) #include <string> #include <iostream> #define Seprtr Console::Informator::Print(Separator, false); #define Emptyc Console::Informator::Empty(); #define Printc(msg) Console::Informator::Print(msg) #define Logc(msg,inf) Console::Informator::Log(msg, inf) #define InfoLogc(msg) Console::Informator::InfoLog(msg) #define ErrorLogc(msg) Console::Informator::ErrorLog(msg) #define Success InfoLogc("Success.") #define Separator "====================================================================" namespace Console { class Informator { public: static void Print(std::string msg, bool date = true) { tm* now = CreateTimeNow(); std::string datestr = date ? ("[" + GetTimeString(*now) + "]") : ""; std::cout << datestr << msg << std::endl; } static void Log(std::string msg, std::string informator) { tm* now = CreateTimeNow(); std::cout << "[" << GetTimeString(*now) << "]" << " " << informator << ": " << msg << std::endl; } static inline void InfoLog(std::string msg) { Log(msg,"INFO"); } static inline void ErrorLog(std::string msg) { Log(msg, "ERROR"); } static inline void Empty() { std::cout << std::endl; } private: static tm* CreateTimeNow(bool utc = false) { time_t raw; time(&raw); tm* now = utc? gmtime(&raw) : localtime(&raw); return now; } static std::string GetTimeString(tm timenow) { return //GetDayString(timenow.tm_wday) + " " + GetMonthString(timenow.tm_mon) + "; " + std::to_string(timenow.tm_hour) + ":" + std::to_string(timenow.tm_min) + ":" + std::to_string(timenow.tm_sec); } static std::string GetMonthString(int month) { month %= 12; switch (month) { case 0: return "Jan"; case 1: return "Feb"; case 2: return "Mar"; case 3: return "Apr"; case 4: return "May"; case 5: return "Jun"; case 6: return "Jul"; case 7: return "Aug"; case 8: return "Sep"; case 9: return "Oct"; case 10: return "Nov"; case 11: return "Dec"; } } static std::string GetDayString(int day) { day %= 7; switch (day) { case 0: return "Mon"; case 1: return "Tue"; case 2: return "Wed"; case 3: return "Thu"; case 4: return "Feb"; case 5: return "Sat"; case 6: return "Sun"; } } }; }
Almeswe/network
server/src/server.h
<gh_stars>0 #pragma once #include "conslog.h" #include <vector> #include <thread> #include <string> #include <winsock2.h> #include <ws2tcpip.h> #define Ok 0 #define Fail 1 #define TcpPackSize 512 #define Panic(msg) Network::ReportError(msg,true) #define Error(msg) Network::ReportError(msg,false) #define SendFromServerTo(client, msg) this->SendDataTo(client, msg, "SERVER") #define SendFromServerToAll(except, msg) this->SendDataTo(this->clients, except, msg, "SERVER") #define SendFromClientToAll(except, msg, from) this->SendDataTo(this->clients, except, msg, from) #define DisconnectAllClients for(ConnectedClient* client : this->clients) this->DisconnectClient(client) namespace Network { int ListenSocket(SOCKET socket, int backlog); int BindSocket(SOCKET socket, sockaddr* addr, int addrSize); SOCKET CreateSocket(int af, int type, int protocol); bool IsEmptyMessage(const char* buffer); void ReportError(std::string msg, bool panic); void CreateAddressHints(int af, int port, std::string ip, sockaddr_in* addr); class ConnectedClient { public: int bufSize; int addrSize; char host[NI_MAXHOST]; char service[NI_MAXSERV]; char buffer[TcpPackSize]; SOCKET socket; sockaddr_in addr; }; class Server { private: int port; int serverAddrSize; WSADATA wsa; SOCKET serverSocket; sockaddr_in serverAddr; std::string ip; std::vector<ConnectedClient*> clients; public: Server(int port, std::string ip); private: ~Server(); public: void Run(); void Stop(); private: int DisconnectClient(ConnectedClient* client); ConnectedClient* GetClientWithSocket(SOCKET socket); int AcceptClient(SOCKET serverSocket, ConnectedClient* client); private: int Init(); void StartListening(); void ExchangeDataWith(ConnectedClient* client); int ReceiveData(ConnectedClient* client); int ProcessData(ConnectedClient* client); int SendDataTo(ConnectedClient* client, std::string buffer, std::string from); int SendDataTo(ConnectedClient* client, const char* buffer, const char* from); int SendDataTo(std::vector<ConnectedClient*> clients, ConnectedClient* exceptTo, const char* buffer, const char* from); int SendDataTo(std::vector<ConnectedClient*> clients, ConnectedClient* exceptTo, std::string buffer, std::string from); }; }
societymedia/SwiftableContainer
Pods/Target Support Files/Pods-SwiftableContainerTests/Pods-SwiftableContainerTests-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SwiftableContainerTestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SwiftableContainerTestsVersionString[];
fccm/ocaml-xlib
src/wrap_xlib.c
/* OCaml bindings for the Xlib library. Copyright (C) 2008, 2009, 2010 by <NAME> printf("monnier.florent@%s", "gmail.<EMAIL>"); OCaml-Xlib is FLOSS software: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software. */ // {{{ Headers #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define CAML_NAME_SPACE 1 #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/bigarray.h> #include <caml/custom.h> #include <caml/fail.h> #include <caml/callback.h> // }}} #include "wrap_xlib.h" // {{{ caml allocs custom_ops(XEvent); custom_ops(XColor); custom_ops(XGCValues); custom_ops(XSetWindowAttributes); custom_ops(XWindowAttributes); custom_ops(XSizeHints); custom_ops(XVisualInfo); custom_ops(XChar2b); custom_ops_n(XChar2b); // }}} // {{{ XID's #define Drawable_val(v) (XID_val(Drawable,(v))) #define Val_Drawable(xid) (Val_XID((xid))) #define Cursor_val(v) (XID_val(Cursor,(v))) #define Val_Cursor(xid) (Val_XID((xid))) #define Colormap_val(v) (XID_val(Colormap,(v))) #define Val_Colormap(xid) (Val_XID((xid))) #define GContext_val(v) (XID_val(GContext,(v))) #define Val_GContext(xid) (Val_XID((xid))) //#define KeySym_val(v) (XID_val(KeySym,(v))) //#define Val_KeySym(xid) (Val_XID((xid))) /* Get keysyms values instead of an abstract type */ #define Val_keysym Val_int #define Keysym_val Long_val // }}} // {{{ return status #define DO_CHECK_RETURN_STATUS 1 #if DO_CHECK_RETURN_STATUS #define GET_STATUS int status = #define CHECK_STATUS(fun,st) \ do{ if (status != st) caml_failwith(#fun ": wrong return status"); }while(0) #else #define GET_STATUS (void) #define CHECK_STATUS #endif /* Many GET/CHECK STATUS are commented just because in * the source code of the Xlib implementation I use (XOrg) * the return status is just static and can only return one * value, so testing it is meaningless. * They are kept commented in case they are meaningfull in * an other implementation. * * Sometime the return value meaning a success is 1 and sometime 0, * even in the commented GET/CHECK_STATUS the value is the good one. */ // }}} // {{{ GC // Handle the finalisation of GC's (other than the default one) #define GC_val(gc_pair) ((GC) Field((gc_pair),0)) #define Display_of_GC(gc_pair) (Field((gc_pair),1)) void Finalize_GC( value gc ) { value dpy = Display_of_GC(gc); if (display_is_open(dpy)) { GET_STATUS XFreeGC( Display_val(dpy), GC_val(gc) ); CHECK_STATUS(XFreeGC,1); } } CAMLprim value do_finalize_GC( value gc ) { Finalize_GC( gc ); return Val_unit; } /* static struct custom_operations fgc_custom_ops = { identifier: "GC handling", finalize: Finalize_GC, compare: custom_compare_default, hash: custom_hash_default, serialize: custom_serialize_default, deserialize: custom_deserialize_default }; */ // The finalised one static inline value Val_GC_final(GC gc, value dpy) { CAMLparam1( dpy ); CAMLlocal1( fgc ); //fgc = caml_alloc_custom( &fgc_custom_ops, 2 * sizeof(value), 0, 1); // the previous line segfaults // so the link is done with do_finalize_GC from the ocaml side fgc = caml_alloc(2, 0); Store_field( fgc, 0, ((value)(gc)) ); Store_field( fgc, 1, dpy ); CAMLreturn( fgc ); } // Not finalised (for default gc) static inline value Val_GC(GC gc, value dpy) { CAMLparam1( dpy ); CAMLlocal1( gcp ); gcp = caml_alloc(2, 0); Store_field( gcp, 0, ((value)(gc)) ); Store_field( gcp, 1, dpy ); CAMLreturn( gcp ); } // }}} // {{{ Event-Masks static const long event_mask_table[] = { KeyPressMask, KeyReleaseMask, ButtonPressMask, ButtonReleaseMask, EnterWindowMask, LeaveWindowMask, PointerMotionMask, PointerMotionHintMask, Button1MotionMask, Button2MotionMask, Button3MotionMask, Button4MotionMask, Button5MotionMask, ButtonMotionMask, KeymapStateMask, ExposureMask, VisibilityChangeMask, StructureNotifyMask, ResizeRedirectMask, SubstructureNotifyMask, SubstructureRedirectMask, FocusChangeMask, PropertyChangeMask, ColormapChangeMask, OwnerGrabButtonMask, }; static inline long Eventmask_val( value em_list ) { long event_mask = 0; while ( em_list != Val_emptylist ) { value head = Field(em_list, 0); long mask = event_mask_table[Long_val(head)]; event_mask |= mask; em_list = Field(em_list, 1); } return event_mask; } static inline value Focus_state_val(value mode) { switch Int_val(mode) { case 0: return RevertToParent; case 1: return RevertToPointerRoot; case 2: return RevertToNone; default: caml_failwith("Unknown focus state value"); } } // }}} // {{{ macro/funcs /* switch this to use the macros or the functions */ //#define XMP(f) X##f // use the functions #define XMP(f) f // use the macros #define _xConnectionNumber XMP(ConnectionNumber) #define _xRootWindow XMP(RootWindow) #define _xDefaultScreen XMP(DefaultScreen) #define _xDefaultRootWindow XMP(DefaultRootWindow) #define _xDefaultVisual XMP(DefaultVisual) #define _xDefaultGC XMP(DefaultGC) #define _xBlackPixel XMP(BlackPixel) #define _xWhitePixel XMP(WhitePixel) #define _xDisplayWidth XMP(DisplayWidth) #define _xDisplayHeight XMP(DisplayHeight) #define _xDisplayPlanes XMP(DisplayPlanes) #define _xDisplayCells XMP(DisplayCells) #define _xScreenCount XMP(ScreenCount) #define _xServerVendor XMP(ServerVendor) #define _xProtocolVersion XMP(ProtocolVersion) #define _xProtocolRevision XMP(ProtocolRevision) #define _xVendorRelease XMP(VendorRelease) #define _xDisplayString XMP(DisplayString) #define _xDefaultDepth XMP(DefaultDepth) #define _xDefaultColormap XMP(DefaultColormap) #define _xBitmapUnit XMP(BitmapUnit) #define _xBitmapBitOrder XMP(BitmapBitOrder) #define _xBitmapPad XMP(BitmapPad) #define _xImageByteOrder XMP(ImageByteOrder) #define _xBitmapUnit XMP(BitmapUnit) #define _xScreenOfDisplay XMP(ScreenOfDisplay) #define _xDefaultScreenOfDisplay XMP(DefaultScreenOfDisplay) #define _xDisplayOfScreen XMP(DisplayOfScreen) #define _xRootWindowOfScreen XMP(RootWindowOfScreen) #define _xBlackPixelOfScreen XMP(BlackPixelOfScreen) #define _xWhitePixelOfScreen XMP(WhitePixelOfScreen) #define _xDefaultColormapOfScreen XMP(DefaultColormapOfScreen) #define _xDefaultDepthOfScreen XMP(DefaultDepthOfScreen) #define _xDefaultGCOfScreen XMP(DefaultGCOfScreen) #define _xDefaultVisualOfScreen XMP(DefaultVisualOfScreen) #define _xWidthOfScreen XMP(WidthOfScreen) #define _xHeightOfScreen XMP(HeightOfScreen) #define _xWidthMMOfScreen XMP(WidthMMOfScreen) #define _xHeightMMOfScreen XMP(HeightMMOfScreen) #define _xPlanesOfScreen XMP(PlanesOfScreen) #define _xCellsOfScreen XMP(CellsOfScreen) #define _xMinCmapsOfScreen XMP(MinCmapsOfScreen) #define _xMaxCmapsOfScreen XMP(MaxCmapsOfScreen) #define _xDoesSaveUnders XMP(DoesSaveUnders) #define _xDoesBackingStore XMP(DoesBackingStore) #define _xEventMaskOfScreen XMP(EventMaskOfScreen) // }}} // {{{ ints // wraps unsigned long #define Pixel_color_val Unsigned_long_val #define Val_pixel_color Val_long // type 'Time' defined in X.h (unsigned long / CARD32) // use int64 instead of int32 because the max value of unsigned is twice // (ocaml int32 is signed) #define Val_time caml_copy_int64 #define Time_val(t) ((Time)Int64_val(t)) // same value than Int64.max_int (used to check Time overflow) // (not used anymore, while CARD32 can not overflow a signed int64) #define MAX_INT64 9223372036854775807L // }}} // {{{ Atom #define Val_Atom(v) ((value)(v)) #define Atom_val(v) ((Atom)(v)) #define Atom_val_addr(v) ((Atom *)(&v)) // }}} // {{{ KeyCode /* There's no real uniformity about the type keycode, - in structures it is most often (int) and sometimes (unsigned int) - in functions sometimes there is the NeedWidePrototypes switch which switches between (unsigned int) and (unsigned char) - in functions sometimes it is just (int) as parameter or (int *) if it's a returned value However as it handles a code for each key of the keyboard, and that generally keyboards have about 105 keys, it seems that it does not really matter. */ #define Val_KeyCode Val_long #define KeyCode_val Long_val // }}} // {{{ caml_copy_string_array_n() // The list provided to caml_copy_string_array() needs to be NULL terminated static value caml_copy_string_array_n(char **strl, int n) { CAMLparam0(); CAMLlocal1(ret); char const **param; int i; param = malloc((n+1) * sizeof(char *)); for (i=0; i<n; i++) { param[i] = strl[i]; } param[n] = NULL; // here the point ret = caml_copy_string_array(param); free(param); CAMLreturn( ret ); } // }}} // TODO: XGetErrorText() #if 0 int ErrorHandler( Display *dpy, XErrorEvent *event ) { char buffer[BUFSIZ]; XGetErrorText(dpy, event->error_code, buffer, BUFSIZ); /* event->request_code; event->minor_code; event->resourceid; event->serial; */ printf("ERROR: %s\n", buffer); return 0; } CAMLprim value ml_XSetErrorHandler( value unit ) { XSetErrorHandler( ErrorHandler ); return Val_unit; } #endif int ErrorHandler_closure( Display *dpy, XErrorEvent *event ) { CAMLparam0(); CAMLlocal1( ml_event ); static value * closure_f = NULL; if (closure_f == NULL) { closure_f = caml_named_value("Error Handler Callback"); } copy_XEvent( event, ml_event ); caml_callback2( *closure_f, Val_Display(dpy), ml_event ); CAMLreturn(0); } CAMLprim value ml_XSetErrorHandler( value unit ) { XSetErrorHandler(ErrorHandler_closure); return Val_unit; } CAMLprim value ml_XlibSpecificationRelease( value unit ) { return Val_int(XlibSpecificationRelease); } CAMLprim value ml_XOpenDisplay( value display_name ) { Display *dpy; dpy = XOpenDisplay( String_val(display_name) ); if (dpy == NULL) { caml_failwith("Cannot open display"); } return Val_Display(dpy); } CAMLprim value ml_XCloseDisplay( value dpy ) { XCloseDisplay( Display_val(dpy) ); display_record_closed(dpy); return Val_unit; } CAMLprim value ml_XFlush( value dpy ) { GET_STATUS XFlush( Display_val(dpy) ); CHECK_STATUS(XFlush, 1); return Val_unit; } CAMLprim value ml_XBell( value dpy, value percent ) { //GET_STATUS XBell( Display_val(dpy), Int_val(percent) ); //CHECK_STATUS(XBell,1); return Val_unit; } CAMLprim value ml_LastKnownRequestProcessed( value dpy ) { return Val_long(LastKnownRequestProcessed(dpy)); } static const int close_mode_table[] = { DestroyAll, RetainPermanent, RetainTemporary, }; #define Close_mode_val(i) (close_mode_table[Long_val(i)]) CAMLprim value ml_XSetCloseDownMode( value dpy, value close_mode ) { //GET_STATUS XSetCloseDownMode( Display_val(dpy), Close_mode_val(close_mode) ); //CHECK_STATUS(XSetCloseDownMode,1); return Val_unit; } CAMLprim value ml_XSync( value dpy, value discard ) { //GET_STATUS XSync( Display_val(dpy), Bool_val(discard) ); //CHECK_STATUS(XSync,1); return Val_unit; } CAMLprim value ml_XGrabServer( value dpy ) { //GET_STATUS XGrabServer( Display_val(dpy) ); //CHECK_STATUS(XGrabServer,1); return Val_unit; } static inline value Val_focus_state(int state) { switch (state) { case RevertToParent: return Val_int(0); case RevertToPointerRoot: return Val_int(1); case RevertToNone: return Val_int(2); default: caml_failwith("unhandled focus state"); } } CAMLprim value ml_XGetInputFocus( value dpy ) { CAMLparam1( dpy ); CAMLlocal1(pair); Window w; int revert_to; XGetInputFocus( Display_val(dpy), &w, &revert_to ); pair = caml_alloc(2, 0); Store_field(pair, 0, (w == None) ? Val_none : Val_some(Val_Window(w))); Store_field(pair, 1, Val_focus_state(revert_to)); CAMLreturn( pair ); } CAMLprim value ml_XUngrabServer( value dpy ) { //GET_STATUS XUngrabServer( Display_val(dpy) ); //CHECK_STATUS(XUngrabServer,1); return Val_unit; } CAMLprim value ml_XUngrabPointer( value dpy, value time ) { //GET_STATUS XUngrabPointer( Display_val(dpy), Time_val(time) ); //CHECK_STATUS(XUngrabPointer,1); return Val_unit; } CAMLprim value ml_XUngrabKeyboard( value dpy, value time ) { //GET_STATUS XUngrabKeyboard( Display_val(dpy), Time_val(time) ); //CHECK_STATUS(XUngrabKeyboard,1); return Val_unit; } CAMLprim value ml_XConnectionNumber( value dpy ) { return Val_int( XConnectionNumber( Display_val(dpy) )); } CAMLprim value ml_XDefaultScreen( value dpy ) { int screen_number = _xDefaultScreen( Display_val(dpy) ); return Val_screenNB(screen_number); } CAMLprim value ml_XScreenCount( value dpy ) { return Val_int( _xScreenCount( Display_val(dpy) )); } CAMLprim value ml_XDefaultRootWindow( value dpy ) { return Val_Window( _xDefaultRootWindow( Display_val(dpy) )); } CAMLprim value ml_XDefaultVisual( value dpy, value screen_number ) { Visual * vis = _xDefaultVisual( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_Visual(vis); } CAMLprim value ml_Visual_visualid( value visual ) { return Val_VisualID( Visual_val(visual)->visualid ); } CAMLprim value ml_Visual_map_entries( value visual ) { return Val_int( Visual_val(visual)->map_entries ); } CAMLprim value ml_Visual_bits_per_rgb( value visual ) { return Val_int( Visual_val(visual)->bits_per_rgb ); } CAMLprim value ml_Visual_red_mask( value visual ) { return Val_long( Visual_val(visual)->red_mask ); } CAMLprim value ml_Visual_green_mask( value visual ) { return Val_long( Visual_val(visual)->green_mask ); } CAMLprim value ml_Visual_blue_mask( value visual ) { return Val_long( Visual_val(visual)->blue_mask ); } CAMLprim value ml_XDefaultDepth( value dpy, value screen_number ) { int depth = _xDefaultDepth( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_int(depth); } CAMLprim value ml_XListDepths( value dpy, value screen_number ) { CAMLparam2(dpy, screen_number); CAMLlocal1(ml_depths); int i, count; int *depths = XListDepths( Display_val(dpy), ScreenNB_val(screen_number), &count ); ml_depths = caml_alloc(count, 0); for (i=0; i<count; ++i) { Store_field( ml_depths, i, Val_int(depths[i]) ); } XFree(depths); CAMLreturn(ml_depths); } CAMLprim value ml_XDisplayPlanes( value dpy, value screen_number ) { int depth = _xDisplayPlanes( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_int(depth); } CAMLprim value ml_XDefaultColormap( value dpy, value screen_number ) { Colormap colormap = _xDefaultColormap( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_Colormap(colormap); } CAMLprim value ml_XDisplayCells( value dpy, value screen_number ) { int cells = _xDisplayCells( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_int(cells); } CAMLprim value ml_XBitmapUnit( value dpy ) { return Val_int( _xBitmapUnit( Display_val(dpy) )); } CAMLprim value ml_XBitmapPad( value dpy ) { return Val_int( _xBitmapPad( Display_val(dpy) )); } CAMLprim value ml_XProtocolVersion( value dpy ) { return Val_int( _xProtocolVersion( Display_val(dpy) )); } CAMLprim value ml_XProtocolRevision( value dpy ) { return Val_int( _xProtocolRevision( Display_val(dpy) )); } CAMLprim value ml_XVendorRelease( value dpy ) { return Val_int( _xVendorRelease( Display_val(dpy) )); } CAMLprim value ml_XServerVendor( value dpy ) { char * vendor = _xServerVendor( Display_val(dpy) ); return caml_copy_string(vendor); } CAMLprim value ml_XBlackPixel( value dpy, value screen_number ) { unsigned long color = _xBlackPixel( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_pixel_color(color); } CAMLprim value ml_XWhitePixel( value dpy, value screen_number ) { unsigned long color = _xWhitePixel( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_pixel_color(color); } CAMLprim value ml_XDisplayWidth( value dpy, value screen_number ) { int width = _xDisplayWidth( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_int(width); } CAMLprim value ml_XDisplayHeight( value dpy, value screen_number ) { int height = _xDisplayHeight( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_int(height); } CAMLprim value ml_XRootWindow( value dpy, value screen_number ) { Window win = _xRootWindow( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_Window(win); } CAMLprim value ml_XDefaultGC( value dpy, value screen_number ) { GC gc = _xDefaultGC( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_GC(gc,dpy); } /* {{{ XColor */ CAMLprim value ml_alloc_XColor( value unit ) { CAMLparam0(); CAMLlocal1(x_color); alloc_XColor(x_color); memset(XColor_val(x_color), 0, sizeof(XColor)); CAMLreturn(x_color); } CAMLprim value ml_XAllocNamedColor( value dpy, value colormap, value color_name ) { CAMLparam3(dpy, colormap, color_name); CAMLlocal3(xcolor_pair, screen_def, exact_def); alloc_XColor(screen_def); alloc_XColor(exact_def); //GET_STATUS XAllocNamedColor( Display_val(dpy), Colormap_val(colormap), String_val(color_name), XColor_val(screen_def), XColor_val(exact_def) ); //CHECK_STATUS(XAllocNamedColor,1); xcolor_pair = caml_alloc(2, 0); Store_field( xcolor_pair, 0, screen_def ); Store_field( xcolor_pair, 1, exact_def ); CAMLreturn(xcolor_pair); } CAMLprim value ml_XColor_set_red( value x_color, value v ) { XColor * xcolor = XColor_val(x_color); xcolor->red = Long_val(v); return Val_unit; } CAMLprim value ml_XColor_set_green( value x_color, value v ) { XColor * xcolor = XColor_val(x_color); xcolor->green = Long_val(v); return Val_unit; } CAMLprim value ml_XColor_set_blue( value x_color, value v ) { XColor * xcolor = XColor_val(x_color); xcolor->blue = Long_val(v); return Val_unit; } CAMLprim value ml_XColor_set_rgb( value x_color, value r, value g, value b ) { XColor * xcolor = XColor_val(x_color); xcolor->red = Long_val(r); xcolor->green = Long_val(g); xcolor->blue = Long_val(b); return Val_unit; } static const char color_flags_table[] = { DoRed, DoGreen, DoBlue, }; CAMLprim value ml_XColor_set_flags( value x_color, value mask_list ) { XColor * xcolor = XColor_val(x_color); while ( mask_list != Val_emptylist ) { value head = Field(mask_list, 0); xcolor->flags |= color_flags_table[Long_val(head)]; mask_list = Field(mask_list, 1); } return Val_unit; } CAMLprim value ml_XAllocColor( value dpy, value colormap, value x_color ) { XColor * xcolor = XColor_val(x_color); XAllocColor( Display_val(dpy), Colormap_val(colormap), xcolor ); return Val_unit; } CAMLprim value ml_XAllocColorCells( value dpy, value colormap, value contig, value nplanes, value npixels ) { CAMLparam5(dpy, colormap, contig, nplanes, npixels); CAMLlocal3(ret, pixels_arr, plnmsk_arr); unsigned long *pixels = NULL; unsigned long *plane_masks = NULL; long i; pixels = malloc(UInt_val(npixels) * sizeof(unsigned long)); if (pixels == NULL) { caml_failwith("xAllocColorCells: out of memory"); } plane_masks = malloc(UInt_val(nplanes) * sizeof(unsigned long)); if (plane_masks == NULL) { free(pixels); caml_failwith("xAllocColorCells: out of memory"); } Status status = XAllocColorCells( Display_val(dpy), Colormap_val(colormap), Bool_val(contig), plane_masks, UInt_val(nplanes), pixels, UInt_val(npixels) ); if (!status) { free(pixels); free(plane_masks); caml_failwith("xAllocColorCells: " "can't alloc enough colors in the current color map"); } pixels_arr = caml_alloc(UInt_val(npixels), 0); for (i=0; i < UInt_val(npixels); ++i) { Store_field( pixels_arr, i, Val_ulong(pixels[i]) ); } free(pixels); plnmsk_arr = caml_alloc(UInt_val(nplanes), 0); for (i=0; i < UInt_val(nplanes); ++i) { Store_field( plnmsk_arr, i, Val_ulong(plane_masks[i]) ); } free(plane_masks); ret = caml_alloc(2, 0); Store_field(ret, 0, pixels_arr ); Store_field(ret, 1, plnmsk_arr ); CAMLreturn(ret); } CAMLprim value ml_XAllocColorCellsPixels( value dpy, value colormap, value contig, value npixels ) { CAMLparam4(dpy, colormap, contig, npixels); CAMLlocal1(pixels_arr); unsigned long *pixels = NULL; long i; pixels = malloc(UInt_val(npixels) * sizeof(unsigned long)); if (pixels == NULL) caml_failwith("xAllocColorCells: out of memory"); Status status = XAllocColorCells( Display_val(dpy), Colormap_val(colormap), Bool_val(contig), NULL, 0, pixels, UInt_val(npixels) ); if (!status) { free(pixels); caml_failwith("xAllocColorCells: " "can't alloc enough colors in the current color map"); } pixels_arr = caml_alloc(UInt_val(npixels), 0); for (i=0; i < UInt_val(npixels); ++i) { Store_field( pixels_arr, i, Val_ulong(pixels[i]) ); } free(pixels); CAMLreturn(pixels_arr); } CAMLprim value ml_XColor_pixel( value x_color ) { XColor * xcolor = XColor_val(x_color); return Val_pixel_color(xcolor->pixel); } CAMLprim value ml_XColor_set_pixel( value x_color, value pixel_color ) { XColor * xcolor = XColor_val(x_color); xcolor->pixel = Pixel_color_val(pixel_color); return Val_unit; } CAMLprim value ml_XQueryColor( value dpy, value colormap, value x_color ) { XQueryColor( Display_val(dpy), Colormap_val(colormap), XColor_val(x_color) ); return Val_unit; } CAMLprim value ml_XColor_get_red( value x_color ) { XColor * xcolor = XColor_val(x_color); return Val_long(xcolor->red); } CAMLprim value ml_XColor_get_green( value x_color ) { XColor * xcolor = XColor_val(x_color); return Val_long(xcolor->green); } CAMLprim value ml_XColor_get_blue( value x_color ) { XColor * xcolor = XColor_val(x_color); return Val_long(xcolor->blue); } CAMLprim value ml_XColor_get_rgb( value x_color ) { CAMLparam1(x_color); CAMLlocal1(rgb); XColor * xcolor = XColor_val(x_color); rgb = caml_alloc(3, 0); Store_field( rgb, 0, Val_long(xcolor->red) ); Store_field( rgb, 1, Val_long(xcolor->green) ); Store_field( rgb, 2, Val_long(xcolor->blue) ); CAMLreturn(rgb); } /* }}} */ CAMLprim value ml_XCreateSimpleWindow( value dpy, value parent, value x, value y, value width, value height, value border_width, value border, value background) { Window win = XCreateSimpleWindow( Display_val(dpy), Window_val(parent), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), UInt_val(border_width), Pixel_color_val(border), Pixel_color_val(background) ); return Val_Window(win); } CAMLprim value ml_XCreateSimpleWindow_bytecode( value * argv, int argn ) { return ml_XCreateSimpleWindow( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8] ); } CAMLprim value ml_XDestroyWindow( value dpy, value win ) { GET_STATUS XDestroyWindow( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XDestroyWindow, 1); return Val_unit; } CAMLprim value caml_get_xid(value xid) { return Val_XID(Long_val(xid)); } CAMLprim value caml_get_xid_of_window(value win) { return Val_long(Window_val(win)); } CAMLprim value ml_alloc_XVisualInfo( value unit ) { CAMLparam0(); CAMLlocal1(visInfo); alloc_XVisualInfo(visInfo); memset(XVisualInfo_val(visInfo), 0, sizeof(XVisualInfo)); CAMLreturn(visInfo); } static const long vinfo_mask_table[] = { VisualNoMask, VisualIDMask, VisualScreenMask, VisualDepthMask, VisualClassMask, VisualRedMaskMask, VisualGreenMaskMask, VisualBlueMaskMask, VisualColormapSizeMask, VisualBitsPerRGBMask, VisualAllMask, }; static inline long vinfo_mask_val( value mask_list ) { long c_mask = 0; while ( mask_list != Val_emptylist ) { value head = Field(mask_list, 0); c_mask |= vinfo_mask_table[Long_val(head)]; mask_list = Field(mask_list, 1); } return c_mask; } CAMLprim value ml_XGetVisualInfo( value dpy, value vinfo_mask, value vinfo_template ) { CAMLparam3(dpy, vinfo_mask, vinfo_template); CAMLlocal2(via, visual_info); int i, nitems; XVisualInfo *visInfo = XGetVisualInfo( Display_val(dpy), vinfo_mask_val(vinfo_mask), XVisualInfo_val(vinfo_template), &nitems ); if (!visInfo) caml_failwith("xGetVisualInfo: can't get visual"); via = caml_alloc(nitems, 0); for (i=0; i<nitems; i++) { alloc_XVisualInfo(visual_info); memcpy(XVisualInfo_val(visual_info), &(visInfo[i]), sizeof(XVisualInfo)); //XFree(visInfo[i]); Store_field(via, i, visual_info); } XFree(visInfo); CAMLreturn(via); } static const int color_class_table[] = { StaticGray, GrayScale, StaticColor, PseudoColor, TrueColor, DirectColor, }; #define Color_class_val(v) (color_class_table[Long_val(v)]) #define XVisualInfo_set_field(Conv_val, field) \ CAMLprim value ml_XVisualInfo_set_##field( value visinfo, value v ) { \ XVisualInfo *vi = XVisualInfo_val(visinfo); \ vi->field = Conv_val(v); \ return Val_unit; \ } XVisualInfo_set_field( Visual_val, visual ) XVisualInfo_set_field( VisualID_val, visualid ) XVisualInfo_set_field( ScreenNB_val, screen ) XVisualInfo_set_field( Long_val, depth ) XVisualInfo_set_field( Color_class_val, class ) XVisualInfo_set_field( ULong_val, red_mask ) XVisualInfo_set_field( ULong_val, green_mask ) XVisualInfo_set_field( ULong_val, blue_mask ) XVisualInfo_set_field( Long_val, colormap_size ) XVisualInfo_set_field( Long_val, bits_per_rgb ) CAMLprim value ml_XMatchVisualInfo( value dpy, value screen, value depth, value color_class ) { CAMLparam4(dpy, screen, depth, color_class); CAMLlocal1(visual_info); alloc_XVisualInfo(visual_info); Status st = XMatchVisualInfo( Display_val(dpy), ScreenNB_val(screen), Int_val(depth), Color_class_val(color_class), XVisualInfo_val(visual_info) ); if (st == False) caml_failwith("xMatchVisualInfo: no visual found"); CAMLreturn(visual_info); } CAMLprim value ml_XVisualInfo_contents( value visual_info ) { CAMLparam1(visual_info); CAMLlocal1(dat); XVisualInfo * vi = XVisualInfo_val(visual_info); dat = caml_alloc(9, 0); Store_field( dat, 0, Val_Visual(vi->visual) ); Store_field( dat, 1, Val_VisualID(vi->visualid) ); Store_field( dat, 2, Val_screenNB(vi->screen) ); Store_field( dat, 3, Val_int(vi->depth) ); Store_field( dat, 4, Val_long(vi->red_mask) ); Store_field( dat, 5, Val_long(vi->green_mask) ); Store_field( dat, 6, Val_long(vi->blue_mask) ); Store_field( dat, 7, Val_int(vi->colormap_size) ); Store_field( dat, 8, Val_int(vi->bits_per_rgb) ); CAMLreturn(dat); } CAMLprim value ml_XFree_XVisualInfo( value visual_info ) { XVisualInfo * vi = XVisualInfo_val(visual_info); if (vi == NULL) { caml_invalid_argument("xFree_xVisualInfo: xVisualInfo NULL pointer"); } else { XFree( vi ); vi = NULL; } return Val_unit; } CAMLprim value ml_XCreateColormap( value dpy, value win, value visual, value alloc ) { Colormap colormap = XCreateColormap( Display_val(dpy), Window_val(win), Visual_val(visual), ( Int_val(alloc) ? AllocAll : AllocNone) ); return Val_Colormap(colormap); } CAMLprim value ml_XFreeColormap( value dpy, value colormap ) { GET_STATUS XFreeColormap( Display_val(dpy), Colormap_val(colormap) ); CHECK_STATUS(XFreeColormap,1); return Val_unit; } CAMLprim value ml_XCopyColormapAndFree( value dpy, value colormap ) { Colormap new_colormap = XCopyColormapAndFree( Display_val(dpy), Colormap_val(colormap) ); /* if ((new_colormap=XCopyColormapAndFree(Display_val(dpy), Colormap_val(colormap))) == BadAlloc) caml_failwith("Can't Create new colormap"); */ return Val_Colormap(new_colormap); } CAMLprim value ml_XSetWindowColormap( value dpy, value win, value colormap ) { GET_STATUS XSetWindowColormap( Display_val(dpy), Window_val(win), Colormap_val(colormap) ); CHECK_STATUS(XSetWindowColormap,1); return Val_unit; } CAMLprim value _ml_XSetWindowAttributes_alloc( value unit ) { CAMLparam0(); CAMLlocal2(ret, wattr); alloc_XSetWindowAttributes(wattr); ret = caml_alloc(2, 0); Store_field(ret, 0, wattr ); Store_field(ret, 1, (value) 0 ); CAMLreturn(ret); } CAMLprim value ml_XSetWindowAttributes_alloc( value unit ) { CAMLparam0(); CAMLlocal1(wattr); alloc_XSetWindowAttributes(wattr); CAMLreturn(wattr); } #define WATTR_SET(field_c_type, attr_field, field_mask, Conv_val, ml_type) \ \ CAMLprim value \ ml_xSetWindowAttributes_set_##attr_field( value ml_wattr, value _##attr_field ) \ { \ XSetWindowAttributes * wattr; \ wattr = XSetWindowAttributes_val(ml_wattr); \ wattr->attr_field = Conv_val(_##attr_field); \ return Val_unit; \ } /* setting the fields of the struct XSetWindowAttributes and the associated mask */ WATTR_SET( Pixmap, background_pixmap, CWBackPixmap, Pixmap_val, pixmap ) WATTR_SET( unsigned long, background_pixel, CWBackPixel, Pixel_color_val, uint ) WATTR_SET( Pixmap, border_pixmap, CWBorderPixmap, Pixmap_val, pixmap ) WATTR_SET( unsigned long, border_pixel, CWBorderPixel, Pixel_color_val, uint ) WATTR_SET( int, bit_gravity, CWBitGravity, Int_val, int ) WATTR_SET( int, win_gravity, CWWinGravity, Int_val, int ) WATTR_SET( int, backing_store, CWBackingStore, Int_val, int ) WATTR_SET( unsigned long, backing_planes, CWBackingPlanes, ULong_val, uint )//XXX WATTR_SET( unsigned long, backing_pixel, CWBackingPixel, ULong_val, uint )//pixel_color? WATTR_SET( Bool, save_under, CWSaveUnder, Bool_val, bool ) WATTR_SET( long, event_mask, CWEventMask, Eventmask_val, event_mask_list ) WATTR_SET( long, do_not_propagate_mask, CWDontPropagate, Long_val, int ) WATTR_SET( Bool, override_redirect, CWOverrideRedirect, Bool_val, bool ) WATTR_SET( Colormap, colormap, CWColormap, Colormap_val, colormap ) WATTR_SET( Cursor, cursor, CWCursor, Cursor_val, cursor ) static const unsigned int window_class_table[] = { CopyFromParent, InputOutput, InputOnly, }; static const unsigned long winattr_valuemask_table[] = { CWBackPixmap, CWBackPixel, CWBorderPixmap, CWBorderPixel, CWBitGravity, CWWinGravity, CWBackingStore, CWBackingPlanes, CWBackingPixel, CWOverrideRedirect, CWSaveUnder, CWEventMask, CWDontPropagate, CWColormap, CWCursor, }; static inline unsigned long winattr_valuemask_val( value mask_list ) { unsigned long c_mask = 0; while ( mask_list != Val_emptylist ) { value head = Field(mask_list, 0); c_mask |= winattr_valuemask_table[Long_val(head)]; mask_list = Field(mask_list, 1); } return c_mask; } CAMLprim value ml_XGetWindowAttributes( value dpy, value win ) { CAMLparam2(dpy, win); CAMLlocal1(wattr); alloc_XWindowAttributes(wattr); //GET_STATUS XGetWindowAttributes( Display_val(dpy), Window_val(win), XWindowAttributes_val(wattr) ); //CHECK_STATUS(XGetWindowAttributes,1); CAMLreturn(wattr); } #define quote(s) #s #define WATTR_GET( Val_conv, field_name, ml_type ) \ \ CAMLprim value \ ml_XWindowAttributes_##field_name( value wattr ) { \ return Val_conv( XWindowAttributes_val(wattr)->field_name ); \ } #define WATTR_GML( Val_conv, field_name, ml_type ) \ external xWindowAttributes_##field_name: xWindowAttributes -> ml_type = quote(ml_XWindowAttributes_##field_name) WATTR_GET( Val_int, x, int ) WATTR_GET( Val_int, y, int ) WATTR_GET( Val_int, width, int ) WATTR_GET( Val_int, height, int ) WATTR_GET( Val_int, depth, int ) WATTR_GET( Val_XScreen, screen, xScreen ) WATTR_GET( Val_int, border_width, int ) WATTR_GET( Val_Colormap, colormap, colormap ) WATTR_GET( Val_bool, map_installed, bool ) CAMLprim value ml_XWindowAttributes_all( value dpy, value win ) { CAMLparam2(dpy, win); CAMLlocal1(wattrs); XWindowAttributes c_wattr; //GET_STATUS XGetWindowAttributes( Display_val(dpy), Window_val(win), &c_wattr ); //CHECK_STATUS(XGetWindowAttributes,1); wattrs = caml_alloc(5, 0); Store_field( wattrs, 0, Val_int( c_wattr.x ) ); Store_field( wattrs, 1, Val_int( c_wattr.y ) ); Store_field( wattrs, 2, Val_int( c_wattr.width ) ); Store_field( wattrs, 3, Val_int( c_wattr.height ) ); Store_field( wattrs, 4, Val_int( c_wattr.depth ) ); CAMLreturn(wattrs); } #if 0 typedef struct { int x, y; /* location of window */ int width, height; /* width and height of window */ int border_width; /* border width of window */ int depth; /* depth of window */ Visual *visual; /* the associated visual structure */ Window root; /* root of screen containing window */ #if defined(__cplusplus) || defined(c_plusplus) int c_class; /* C++ InputOutput, InputOnly*/ #else int class; /* InputOutput, InputOnly*/ #endif int bit_gravity; /* one of bit gravity values */ int win_gravity; /* one of the window gravity values */ int backing_store; /* NotUseful, WhenMapped, Always */ unsigned long backing_planes;/* planes to be preserved if possible */ unsigned long backing_pixel;/* value to be used when restoring planes */ Bool save_under; /* boolean, should bits under be saved? */ Colormap colormap; /* color map to be associated with window */ Bool map_installed; /* boolean, is color map currently installed*/ int map_state; /* IsUnmapped, IsUnviewable, IsViewable */ long all_event_masks; /* set of events all people have interest in*/ long your_event_mask; /* my event mask */ long do_not_propagate_mask; /* set of events that should not propagate */ Bool override_redirect; /* boolean value for override-redirect */ Screen *screen; /* back pointer to correct screen */ } XWindowAttributes; #endif CAMLprim value ml_XCreateWindow( value dpy, value parent, value x, value y, value width, value height, value border_width, value depth, value class, value visual, value valuemask, value attributes ) { Window win = XCreateWindow( Display_val(dpy), Window_val(parent), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), UInt_val(border_width), Int_val(depth), window_class_table[Long_val(class)], Visual_val(visual), winattr_valuemask_val(valuemask), XSetWindowAttributes_val(attributes) ); if (!win) caml_failwith("XCreateWindow"); return Val_Window(win); } CAMLprim value ml_XCreateWindow_bytecode( value * argv, int argn ) { return ml_XCreateWindow( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11] ); } CAMLprim value ml_XResizeWindow( value dpy, value win, value width, value height ) { GET_STATUS XResizeWindow( Display_val(dpy), Window_val(win), UInt_val(width), UInt_val(height) ); CHECK_STATUS(XResizeWindow,1); return Val_unit; } CAMLprim value ml_XMoveWindow( value dpy, value win, value x, value y ) { GET_STATUS XMoveWindow( Display_val(dpy), Window_val(win), Int_val(x), Int_val(y) ); CHECK_STATUS(XMoveWindow,1); return Val_unit; } CAMLprim value ml_XMoveResizeWindow( value dpy, value win, value x, value y, value width, value height ) { GET_STATUS XMoveResizeWindow( Display_val(dpy), Window_val(win), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height) ); CHECK_STATUS(XMoveResizeWindow,1); return Val_unit; } CAMLprim value ml_XMoveResizeWindow_bytecode( value * argv, int argn ) { return ml_XMoveResizeWindow( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XLowerWindow( value dpy, value win ) { GET_STATUS XLowerWindow( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XLowerWindow,1); return Val_unit; } CAMLprim value ml_XRaiseWindow( value dpy, value win ) { GET_STATUS XRaiseWindow( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XRaiseWindow,1); return Val_unit; } CAMLprim value ml_XStoreName( value dpy, value win, value name ) { GET_STATUS XStoreName( Display_val(dpy), Window_val(win), String_val(name) ); CHECK_STATUS(XStoreName, 1); return Val_unit; } CAMLprim value ml_XFetchName( value dpy, value win ) { CAMLparam2( dpy, win ); CAMLlocal1( ml_window_name ); char * window_name = NULL; //GET_STATUS XFetchName( Display_val(dpy), Window_val(win), &window_name ); //CHECK_STATUS(XFetchName,1); if (window_name != NULL) { ml_window_name = caml_copy_string(window_name); XFree(window_name); } else { caml_failwith("xFetchName"); } CAMLreturn( ml_window_name ); } CAMLprim value ml_XSelectInput( value dpy, value win, value ml_event_mask ) { long event_mask = Eventmask_val( ml_event_mask ); GET_STATUS XSelectInput( Display_val(dpy), Window_val(win), event_mask ); CHECK_STATUS(XSelectInput, 1); return Val_unit; } CAMLprim value ml_XMapWindow( value dpy, value win ) { GET_STATUS XMapWindow( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XMapWindow, 1); return Val_unit; } CAMLprim value ml_XMapSubwindows( value dpy, value win ) { GET_STATUS XMapSubwindows( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XMapSubwindows, 1); return Val_unit; } CAMLprim value ml_XMapRaised( value dpy, value win ) { //GET_STATUS XMapRaised( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XMapRaised, 1); return Val_unit; } CAMLprim value ml_XUnmapWindow( value dpy, value win ) { //GET_STATUS XUnmapWindow( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XUnmapWindow,1); return Val_unit; } CAMLprim value ml_XReparentWindow( value dpy, value win, value parent, value x, value y ) { GET_STATUS XReparentWindow( Display_val(dpy), Window_val(win), Window_val(parent), Int_val(x), Int_val(y) ); CHECK_STATUS(XReparentWindow,1); return Val_unit; } CAMLprim value ml_XChangeSaveSet( value dpy, value win, value change_mode ) { //GET_STATUS XChangeSaveSet( Display_val(dpy), Window_val(win), (Int_val(change_mode) ? SetModeDelete : SetModeInsert) ); //CHECK_STATUS(XChangeSaveSet,1); return Val_unit; } CAMLprim value ml_XAddToSaveSet( value dpy, value win ) { //GET_STATUS XAddToSaveSet( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XAddToSaveSet,1); return Val_unit; } CAMLprim value ml_XRemoveFromSaveSet( value dpy, value win ) { //GET_STATUS XRemoveFromSaveSet( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XRemoveFromSaveSet,1); return Val_unit; } CAMLprim value ml_XQueryTree( value dpy, value win ) { CAMLparam2( dpy, win ); CAMLlocal2( ret, children_arr ); Window root_win, parent_win, *children; unsigned int nchildren, i; children = NULL; Status status = XQueryTree( Display_val(dpy), Window_val(win), &root_win, &parent_win, &children, &nchildren ); if (status != 1) { if (children != NULL) XFree(children); caml_failwith("xQueryTree"); } children_arr = caml_alloc(nchildren, 0); for (i=0; i < nchildren; i++) { Store_field( children_arr, i, Val_Window(children[i]) ); } XFree(children); ret = caml_alloc(3, 0); Store_field( ret, 0, Val_Window(root_win) ); Store_field( ret, 1, Val_Window(parent_win) ); Store_field( ret, 2, children_arr ); CAMLreturn( ret ); } CAMLprim value ml_XRestackWindows( value dpy, value ml_wins ) { int nwindows, i; Window* windows; nwindows = Wosize_val(ml_wins); windows = malloc(nwindows * sizeof(Window*)); for (i=0; i < nwindows; i++) { windows[i] = Window_val(Field(ml_wins, i)); } //GET_STATUS XRestackWindows( Display_val(dpy), windows, nwindows ); free(windows); //CHECK_STATUS(XRestackWindows,1); return Val_unit; } static const int circulateSubwinsDir_table[] = { RaiseLowest, LowerHighest }; #define CirculateSubwinsDir_val(i) (circulateSubwinsDir_table[Long_val(i)]) CAMLprim value ml_XCirculateSubwindows( value dpy, value win, value dir ) { //GET_STATUS XCirculateSubwindows( Display_val(dpy), Window_val(win), CirculateSubwinsDir_val(dir) ); //CHECK_STATUS(XCirculateSubwindows,1); return Val_unit; } CAMLprim value ml_XCirculateSubwindowsDown( value dpy, value win ) { //GET_STATUS XCirculateSubwindowsDown( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XCirculateSubwindowsDown,1); return Val_unit; } CAMLprim value ml_XCirculateSubwindowsUp( value dpy, value win ) { //GET_STATUS XCirculateSubwindowsUp( Display_val(dpy), Window_val(win) ); //CHECK_STATUS(XCirculateSubwindowsUp,1); return Val_unit; } CAMLprim value ml_XGetWindowProperty_string( value dpy, value win, value property, value long_offset, value long_length, value delete, value req_type ) { CAMLparam5(dpy, win, property, long_offset, long_length); CAMLxparam2(delete, req_type); CAMLlocal1(ret); Atom actual_type; int actual_format; unsigned long nitems, bytes_after; /*unsigned*/ char* prop; (void) XGetWindowProperty( Display_val(dpy), Window_val(win), Atom_val(property), Long_val(long_offset), Long_val(long_length), Bool_val(delete), AnyPropertyType, // Atom req_type, TODO &actual_type, &actual_format, &nitems, &bytes_after, (unsigned char**)&prop ); ret = caml_alloc(5, 0); Store_field(ret, 0, Val_Atom(actual_type) ); Store_field(ret, 1, Val_int(actual_format) ); Store_field(ret, 2, Val_long(nitems) ); Store_field(ret, 3, Val_long(bytes_after) ); Store_field(ret, 4, caml_copy_string(prop) ); XFree(prop); CAMLreturn(ret); } CAMLprim value ml_XGetWindowProperty_string_bytecode( value * argv, int argn ) { return ml_XGetWindowProperty_string( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_XGetWindowProperty_window( value dpy, value win, value property, value long_offset, value long_length, value delete, value req_type ) { CAMLparam5(dpy, win, property, long_offset, long_length); CAMLxparam2(delete, req_type); CAMLlocal1(ret); Atom actual_type; int actual_format; unsigned long nitems, bytes_after; Window *prop; (void) XGetWindowProperty( Display_val(dpy), Window_val(win), Atom_val(property), Long_val(long_offset), Long_val(long_length), Bool_val(delete), AnyPropertyType, // Atom req_type, TODO &actual_type, &actual_format, &nitems, &bytes_after, (unsigned char**)&prop ); ret = caml_alloc(5, 0); Store_field(ret, 0, Val_Atom(actual_type) ); Store_field(ret, 1, Val_int(actual_format) ); Store_field(ret, 2, Val_long(nitems) ); Store_field(ret, 3, Val_long(bytes_after) ); Store_field(ret, 4, Val_Window(prop[0]) ); XFree(prop); CAMLreturn(ret); } CAMLprim value ml_XGetWindowProperty_window_bytecode( value * argv, int argn ) { return ml_XGetWindowProperty_window( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_hasWindowProperty( value dpy, value win, value property ) { Atom actual_type; Atom expected_type = Atom_val(property); int actual_format; unsigned long nitems, bytes_after; Window *prop; int result = XGetWindowProperty( Display_val(dpy), Window_val(win), expected_type, Long_val(0), // offset Long_val(0), // length 0, // delete expected_type, &actual_type, &actual_format, &nitems, &bytes_after, (unsigned char**)&prop ); if (result != Success) return Val_false; XFree(prop); if (actual_type != property) return Val_false; return Val_true; } /* Managing Installed Colormaps */ CAMLprim value ml_XInstallColormap( value dpy, value colormap ) { //GET_STATUS XInstallColormap( Display_val(dpy), Colormap_val(colormap) ); //CHECK_STATUS(XInstallColormap,1); return Val_unit; } CAMLprim value ml_XUninstallColormap( value dpy, value colormap ) { //GET_STATUS XUninstallColormap( Display_val(dpy), Colormap_val(colormap) ); //CHECK_STATUS(XUninstallColormap,1); return Val_unit; } CAMLprim value ml_XListInstalledColormaps( value dpy, value win ) { CAMLparam2(dpy, win); CAMLlocal1(ret); int i, num; Colormap *colormaps = XListInstalledColormaps( Display_val(dpy), Window_val(win), &num ); ret = caml_alloc(num, 0); for (i=0; i<num; ++i) { Store_field(ret, i, Val_Colormap(colormaps[i]) ); } XFree(colormaps); CAMLreturn(ret); } CAMLprim value ml_XKillClient( value dpy, value resource ) { //GET_STATUS XKillClient( Display_val(dpy), (XID) resource ); //CHECK_STATUS(XKillClient,1); return Val_unit; } /* Threads */ CAMLprim value ml_XInitThreads( value unit ) { GET_STATUS XInitThreads(); CHECK_STATUS(XInitThreads,1); return Val_unit; } CAMLprim value ml_XLockDisplay( value dpy ) { XLockDisplay( Display_val(dpy) ); return Val_unit; } CAMLprim value ml_XUnlockDisplay( value dpy ) { XUnlockDisplay( Display_val(dpy) ); return Val_unit; } CAMLprim value ml_XSetWMProtocols( value dpy, value win, value protocols, value count ) { Status status = XSetWMProtocols( Display_val(dpy), Window_val(win), Atom_val_addr(protocols), Int_val(count) ); CHECK_STATUS(XSetWMProtocols, 1); return Val_unit; } CAMLprim value ml_XInternAtom( value dpy, value atom_name, value only_if_exists ) { Atom a = XInternAtom( Display_val(dpy), String_val(atom_name), Bool_val(only_if_exists) ); if (a == None) caml_raise_not_found(); // XInternAtom() can generate BadAlloc and BadValue errors. return Val_Atom(a); } CAMLprim value ml_XInternAtoms( value dpy, value ml_names, value only_if_exists ) { CAMLparam3(dpy, ml_names, only_if_exists); CAMLlocal1(ret); int count, i; char** names; Atom* atoms_return; count = Wosize_val(ml_names); atoms_return = malloc(count * sizeof(Atom)); names = malloc(count * sizeof(char *)); for (i=0; i<count; ++i) { names[i] = String_val(Field(ml_names,i)); } Status st = XInternAtoms( Display_val(dpy), names, count, Bool_val(only_if_exists), atoms_return ); if (st == 0) caml_failwith("xInternAtoms: atoms were not returned for all of the names"); ret = caml_alloc(count, 0); for (i=0; i<count; ++i) { Store_field( ret, i, Val_Atom(atoms_return[i]) ); } free(atoms_return); free(names); CAMLreturn(ret); } CAMLprim value ml_XGetAtomName( value dpy, value atom ) { CAMLparam2(dpy, atom); CAMLlocal1(ml_atom_name); char * atom_name = XGetAtomName( Display_val(dpy), Atom_val(atom) ); if (atom_name == NULL) caml_failwith("xGetAtomName"); ml_atom_name = caml_copy_string(atom_name); XFree((void *)atom_name); CAMLreturn(ml_atom_name); } /* XSizeHints, from <X11/Xutil.h> */ CAMLprim value ml_alloc_XSizeHints( value unit ) { CAMLparam0(); CAMLlocal1(size_hints); alloc_XSizeHints(size_hints); memset(XSizeHints_val(size_hints), 0, sizeof(XSizeHints)); CAMLreturn(size_hints); } CAMLprim value ml_XSizeHints_set_USPosition( value size_hints, value _x, value _y ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= USPosition; sh->x = Int_val(_x); sh->y = Int_val(_y); return Val_unit; } CAMLprim value ml_XSizeHints_set_PPosition( value size_hints, value _x, value _y ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PPosition; sh->x = Int_val(_x); sh->y = Int_val(_y); return Val_unit; } CAMLprim value ml_XSizeHints_set_USSize( value size_hints, value _width, value _height ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= USSize; sh->width = Int_val(_width); sh->height = Int_val(_height); return Val_unit; } CAMLprim value ml_XSizeHints_set_PSize( value size_hints, value _width, value _height ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PSize; sh->width = Int_val(_width); sh->height = Int_val(_height); return Val_unit; } CAMLprim value ml_XSizeHints_set_PMinSize( value size_hints, value _min_width, value _min_height ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PMinSize; sh->min_width = Int_val(_min_width); sh->min_height = Int_val(_min_height); return Val_unit; } CAMLprim value ml_XSizeHints_set_PMaxSize( value size_hints, value _max_width, value _max_height ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PMaxSize; sh->max_width = Int_val(_max_width); sh->max_height = Int_val(_max_height); return Val_unit; } CAMLprim value ml_XSizeHints_set_PResizeInc( value size_hints, value _width_inc, value _height_inc ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PResizeInc; sh->width_inc = Int_val(_width_inc); sh->height_inc = Int_val(_height_inc); return Val_unit; } CAMLprim value ml_XSizeHints_set_PBaseSize( value size_hints, value _base_width, value _base_height ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PBaseSize; sh->base_width = Int_val(_base_width); sh->base_height = Int_val(_base_height); return Val_unit; } CAMLprim value ml_XSizeHints_set_PAspect( value size_hints, value min_aspect, value max_aspect ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PAspect; sh->min_aspect.x = Int_val(Field(min_aspect,0)); sh->min_aspect.y = Int_val(Field(min_aspect,1)); sh->max_aspect.x = Int_val(Field(max_aspect,0)); sh->max_aspect.y = Int_val(Field(max_aspect,1)); return Val_unit; } CAMLprim value ml_XSizeHints_set_PWinGravity( value size_hints, value _win_gravity ) { XSizeHints *sh; sh = XSizeHints_val(size_hints); sh->flags |= PWinGravity; sh->win_gravity = Int_val(_win_gravity); return Val_unit; } CAMLprim value ml_XSetNormalHints( value dpy, value win, value size_hints ) { XSizeHints* hints; hints = XSizeHints_val(size_hints); GET_STATUS XSetNormalHints( Display_val(dpy), Window_val(win), hints ); CHECK_STATUS(XSetNormalHints,1); return Val_unit; } CAMLprim value ml_XSetStandardProperties( value dpy, value win, value window_name, value icon_name, value ml_icon_pixmap, value ml_argv, value hints ) { int argc = Wosize_val(ml_argv); char ** argv = malloc((argc+1) * sizeof(char*)); int i; for (i=0; i<argc; i++) { value ml_arg = Field(ml_argv,i); int len = caml_string_length(ml_arg); char *arg = String_val(ml_arg); argv[i] = malloc((len+1) * sizeof(char)); strncpy(argv[i], arg, len); argv[i][len] = '\0'; } argv[argc] = NULL; Pixmap icon_pixmap; if (ml_icon_pixmap == Val_int(0)) icon_pixmap = None; // None else icon_pixmap = Pixmap_val( Field(ml_icon_pixmap,0) ); // Some v GET_STATUS XSetStandardProperties( Display_val(dpy), Window_val(win), String_val(window_name), String_val(icon_name), icon_pixmap, argv, argc, XSizeHints_val(hints) ); for (i=0; i<argc; ++i) { free(argv[i]); } free(argv); CHECK_STATUS(XSetStandardProperties,1); return Val_unit; } CAMLprim value ml_XSetStandardProperties_bytecode( value * argv, int argn ) { return ml_XSetStandardProperties( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_alloc_XGCValues( value unit ) { CAMLparam0(); CAMLlocal1(gcv); alloc_XGCValues(gcv); memset(XGCValues_val(gcv), 0, sizeof(XGCValues)); CAMLreturn(gcv); } static const unsigned long gc_valuemask_table[] = { GCFunction, GCPlaneMask, GCForeground, GCBackground, GCLineWidth, GCLineStyle, GCCapStyle, GCJoinStyle, GCFillStyle, GCFillRule, GCTile, GCStipple, GCTileStipXOrigin, GCTileStipYOrigin, GCFont, GCSubwindowMode, GCGraphicsExposures, GCClipXOrigin, GCClipYOrigin, GCClipMask, GCDashOffset, GCDashList, GCArcMode, }; static inline unsigned long gc_valuemask_val( value mask_list ) { unsigned long c_mask = 0; while ( mask_list != Val_emptylist ) { value head = Field(mask_list, 0); c_mask |= gc_valuemask_table[Long_val(head)]; mask_list = Field(mask_list, 1); } return c_mask; } CAMLprim value ml_XCreateGC( value dpy, value d, value valuemask, value gc_values ) { CAMLparam4( dpy, d, valuemask, gc_values ); GC gc = XCreateGC( Display_val(dpy), Drawable_val(d), gc_valuemask_val(valuemask), XGCValues_val(gc_values) ); if (!gc) caml_failwith("xCreateGC: out of memory"); CAMLreturn( Val_GC_final(gc,dpy) ); } CAMLprim value ml_XChangeGC( value dpy, value gc, value valuemask, value gc_values ) { //GET_STATUS XChangeGC( Display_val(dpy), GC_val(gc), gc_valuemask_val(valuemask), XGCValues_val(gc_values) ); //CHECK_STATUS(XChangeGC,1); return Val_unit; } CAMLprim value ml_XGetGCValues( value dpy, value gc, value valuemask ) { CAMLparam3(dpy, gc, valuemask); CAMLlocal1(gcv); alloc_XGCValues(gcv); GET_STATUS XGetGCValues( Display_val(dpy), GC_val(gc), gc_valuemask_val(valuemask), XGCValues_val(gcv) ); CHECK_STATUS(XGetGCValues,True); CAMLreturn(gcv); } static const int logical_operation_function_table[] = { GXclear, GXand, GXandReverse, GXcopy, GXandInverted, GXnoop, GXxor, GXor, GXnor, GXequiv, GXinvert, GXorReverse, GXcopyInverted, GXorInverted, GXnand, GXset }; #define Function_val(i) (logical_operation_function_table[Long_val(i)]) static inline value Val_function(int function) { switch (function) { case GXclear: return Val_int(0); case GXand: return Val_int(1); case GXandReverse: return Val_int(2); case GXcopy: return Val_int(3); case GXandInverted: return Val_int(4); case GXnoop: return Val_int(5); case GXxor: return Val_int(6); case GXor: return Val_int(7); case GXnor: return Val_int(8); case GXequiv: return Val_int(9); case GXinvert: return Val_int(10); case GXorReverse: return Val_int(11); case GXcopyInverted: return Val_int(12); case GXorInverted: return Val_int(13); case GXnand: return Val_int(14); case GXset: return Val_int(15); } return Val_int(0); } static const int line_style_table[] = { LineSolid, LineOnOffDash, LineDoubleDash }; #define Line_style_val(i) (line_style_table[Long_val(i)]) static inline value Val_line_style(int line_style) { switch (line_style) { case LineSolid: return Val_int(0); case LineOnOffDash: return Val_int(1); case LineDoubleDash: return Val_int(2); } return Val_int(0); } static const int cap_style_table[] = { CapNotLast, CapButt, CapRound, CapProjecting }; #define Cap_style_val(i) (cap_style_table[Long_val(i)]) static inline value Val_cap_style(int cap_style) { switch (cap_style) { case CapNotLast: return Val_int(0); case CapButt: return Val_int(1); case CapRound: return Val_int(2); case CapProjecting: return Val_int(3); } return Val_int(0); } static const int join_style_table[] = { JoinMiter, JoinRound, JoinBevel }; #define Join_style_val(i) (join_style_table[Long_val(i)]) static inline value Val_join_style(int join_style) { switch (join_style) { case JoinMiter: return Val_int(0); case JoinRound: return Val_int(1); case JoinBevel: return Val_int(2); } return Val_int(0); } static const int fill_style_table[] = { FillSolid, FillTiled, FillStippled, FillOpaqueStippled }; #define Fill_style_val(i) (fill_style_table[Long_val(i)]) static inline value Val_fill_style(int fill_style) { switch (fill_style) { case FillSolid: return Val_int(0); case FillTiled: return Val_int(1); case FillStippled: return Val_int(2); case FillOpaqueStippled: return Val_int(3); } return Val_int(0); } static const int fill_rule_table[] = { EvenOddRule, WindingRule }; #define Fill_rule_val(i) (fill_rule_table[Long_val(i)]) static inline value Val_fill_rule(int fill_rule) { switch (fill_rule) { case EvenOddRule: return Val_int(0); case WindingRule: return Val_int(1); } return Val_int(0); } static const int arc_mode_table[] = { ArcChord, ArcPieSlice }; #define Arc_mode_val(i) (arc_mode_table[Long_val(i)]) static inline value Val_arc_mode(int arc_mode) { switch (arc_mode) { case ArcChord: return Val_int(0); case ArcPieSlice: return Val_int(1); } return Val_int(0); } static const int subwindow_mode_table[] = { ClipByChildren, IncludeInferiors }; #define Subwindow_mode_val(i) (subwindow_mode_table[Long_val(i)]) static inline value Val_subwindow_mode(int subwindow_mode) { switch (subwindow_mode) { case ClipByChildren: return Val_int(0); case IncludeInferiors: return Val_int(1); } return Val_int(0); } #define GCVAL_SET(field_c_type, field_name, Conv_val, Val_conv, ml_type, mask) \ \ CAMLprim value \ ml_XGCValues_set_##field_name( value ml_gcv, value v ) \ { \ XGCValues * gcv; \ gcv = XGCValues_val(ml_gcv); \ gcv->field_name = Conv_val(v); \ return Val_unit; \ } #define GCVAL_GET(field_c_type, field_name, Conv_val, Val_conv, ml_type, mask) \ \ CAMLprim value \ ml_XGCValues_get_##field_name( value ml_gcv, value v ) \ { \ XGCValues * gcv; \ gcv = XGCValues_val(ml_gcv); \ return Val_conv( gcv->field_name ); \ } #define GCVAL_SML(field_c_type, field_name, Conv_val, Val_conv, ml_type, mask) \ external xGCValues_set_##field_name: gcv:xGCValues -> ml_type -> unit = quote(ml_XGCValues_set_##field_name) #define GCVAL_GML(field_c_type, field_name, Conv_val, Val_conv, ml_type, mask) \ external xGCValues_get_##field_name: gcv:xGCValues -> ml_type = quote(ml_XGCValues_get_##field_name) GCVAL_SET( unsigned long, foreground, Pixel_color_val, Val_pixel_color, pixel_color, GCForeground ) GCVAL_SET( unsigned long, background, Pixel_color_val, Val_pixel_color, pixel_color, GCBackground ) GCVAL_SET( Bool, graphics_exposures, Bool_val, Val_bool, bool, GCGraphicsExposures ) GCVAL_SET( Pixmap, tile, Pixmap_val, Val_Pixmap, pixmap, GCTile ) GCVAL_SET( int, clip_x_origin, Int_val, Val_int, int, GCClipXOrigin ) GCVAL_SET( int, clip_y_origin, Int_val, Val_int, int, GCClipYOrigin ) GCVAL_SET( int, ts_x_origin, Int_val, Val_int, int, GCTileStipXOrigin ) GCVAL_SET( int, ts_y_origin, Int_val, Val_int, int, GCTileStipYOrigin ) GCVAL_SET( int, line_style, Line_style_val, Val_line_style, line_style, GCLineStyle ) GCVAL_SET( int, cap_style, Cap_style_val, Val_cap_style, cap_style, GCCapStyle ) GCVAL_SET( int, join_style, Join_style_val, Val_join_style, join_style, GCJoinStyle ) GCVAL_SET( int, fill_style, Fill_style_val, Val_fill_style, fill_style, GCFillStyle ) GCVAL_SET( int, fill_rule, Fill_rule_val, Val_fill_rule, fill_rule, GCFillRule ) GCVAL_SET( int, function, Function_val, Val_function, logop_func, GCFunction ) GCVAL_SET( int, line_width, Int_val, Val_int, int, GCLineWidth ) GCVAL_SET( int, arc_mode, Arc_mode_val, Val_arc_mode, arc_mode, GCArcMode ) GCVAL_SET( Font, font, Font_val, Val_Font, font, GCFont ) GCVAL_SET( int, subwindow_mode, Subwindow_mode_val, Val_subwindow_mode, subwindow_mode, GCSubwindowMode ) GCVAL_GET( unsigned long, foreground, Pixel_color_val, Val_pixel_color, pixel_color, GCForeground ) GCVAL_GET( unsigned long, background, Pixel_color_val, Val_pixel_color, pixel_color, GCBackground ) GCVAL_GET( Bool, graphics_exposures, Bool_val, Val_bool, bool, GCGraphicsExposures ) GCVAL_GET( Pixmap, tile, Pixmap_val, Val_Pixmap, pixmap, GCTile ) GCVAL_GET( int, clip_x_origin, Int_val, Val_int, int, GCClipXOrigin ) GCVAL_GET( int, clip_y_origin, Int_val, Val_int, int, GCClipYOrigin ) GCVAL_GET( int, ts_x_origin, Int_val, Val_int, int, GCTileStipXOrigin ) GCVAL_GET( int, ts_y_origin, Int_val, Val_int, int, GCTileStipYOrigin ) GCVAL_GET( int, line_style, Line_style_val, Val_line_style, line_style, GCLineStyle ) GCVAL_GET( int, cap_style, Cap_style_val, Val_cap_style, cap_style, GCCapStyle ) GCVAL_GET( int, join_style, Join_style_val, Val_join_style, join_style, GCJoinStyle ) GCVAL_GET( int, fill_style, Fill_style_val, Val_fill_style, fill_style, GCFillStyle ) GCVAL_GET( int, fill_rule, Fill_rule_val, Val_fill_rule, fill_rule, GCFillRule ) GCVAL_GET( int, function, Function_val, Val_function, logop_func, GCFunction ) GCVAL_GET( int, line_width, Int_val, Val_int, int, GCLineWidth ) GCVAL_GET( int, arc_mode, Arc_mode_val, Val_arc_mode, arc_mode, GCArcMode ) GCVAL_GET( Font, font, Font_val, Val_Font, font, GCFont ) GCVAL_GET( int, subwindow_mode, Subwindow_mode_val, Val_subwindow_mode, subwindow_mode, GCSubwindowMode ) /* | GCPlaneMask | GCStipple | GCClipMask | GCDashOffset | GCDashList */ #if 0 XGCValues gcv; gcv.plane_mask = 0x1; gcv.stipple = bitmap; gcv.clip_mask = bitmap; gcv.dash_offset = 1; gcv.dashes = 0xc2; GC gc = XCreateGC(dpy, w, GCFunction | GCPlaneMask | GCForeground | GCBackground | GCLineWidth | GCLineStyle | GCCapStyle | GCJoinStyle | GCFillStyle | GCFillRule | GCTile | GCStipple | GCTileStipXOrigin | GCTileStipYOrigin | GCFont | GCSubwindowMode | GCGraphicsExposures | GCClipXOrigin | GCClipYOrigin | GCClipMask | GCDashOffset | GCDashList | GCArcMode, &gcv); unsigned long plane_mask;/* plane mask */ Pixmap stipple; /* stipple 1 plane pixmap for stipping */ int subwindow_mode; /* ClipByChildren, IncludeInferiors */ Pixmap clip_mask; /* bitmap clipping; other calls for rects */ int dash_offset; /* patterned/dashed line information */ char dashes; #endif CAMLprim value ml_XSetForeground( value dpy, value gc, value foreground ) { GET_STATUS XSetForeground( Display_val(dpy), GC_val(gc), Pixel_color_val(foreground) ); CHECK_STATUS(XSetForeground,1); return Val_unit; } CAMLprim value ml_XSetBackground( value dpy, value gc, value background ) { GET_STATUS XSetBackground( Display_val(dpy), GC_val(gc), Pixel_color_val(background) ); CHECK_STATUS(XSetBackground,1); return Val_unit; } CAMLprim value ml_XSetLineAttributes( value dpy, value gc, value line_width, value line_style, value cap_style, value join_style ) { GET_STATUS XSetLineAttributes( Display_val(dpy), GC_val(gc), UInt_val(line_width), Line_style_val(line_style), Cap_style_val(cap_style), Join_style_val(join_style) ); CHECK_STATUS(XSetLineAttributes,1); return Val_unit; } CAMLprim value ml_XSetLineAttributes_bytecode( value * argv, int argn ) { return ml_XSetLineAttributes( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XSetFillStyle( value dpy, value gc, value fill_style ) { XSetFillStyle( Display_val(dpy), GC_val(gc), Fill_style_val(fill_style) ); return Val_unit; } CAMLprim value ml_XClearWindow( value dpy, value win ) { GET_STATUS XClearWindow( Display_val(dpy), Window_val(win) ); CHECK_STATUS(XClearWindow,1); return Val_unit; } CAMLprim value ml_XClearArea( value dpy, value win, value x, value y, value width, value height, value exposures ) { //GET_STATUS XClearArea( Display_val(dpy), Window_val(win), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), Bool_val(exposures) ); //CHECK_STATUS(XClearArea,1); return Val_unit; } CAMLprim value ml_XClearArea_bytecode( value * argv, int argn ) { return ml_XClearArea( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } /* TODO: Max number of elements: XDrawLines() points: XMaxRequestSize(dpy) - 3 XFillPolygon() points: XMaxRequestSize(dpy) - 4 XDrawSegments() segments: (XMaxRequestSize(dpy) - 3) / 2 XDrawRectangles() rectangles: (XMaxRequestSize(dpy) - 3) / 2 XFillRectangles() rectangles: (XMaxRequestSize(dpy) - 3) / 2 XDrawArcs() or XFillArcs() arcs: (XMaxRequestSize(dpy) - 3) / 3 */ CAMLprim value ml_XDrawArc( value dpy, value d, value gc, value x, value y, value width, value height, value angle1, value angle2 ) { GET_STATUS XDrawArc( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), Int_val(angle1), Int_val(angle2) ); CHECK_STATUS(XDrawArc, 1); return Val_unit; } CAMLprim value ml_XDrawArc_bytecode( value * argv, int argn ) { return ml_XDrawArc( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8] ); } CAMLprim value ml_XDrawArcs( value dpy, value d, value gc, value ml_arcs ) { int i, narcs = Wosize_val(ml_arcs); XArc * arcs = malloc(narcs * sizeof(XArc)); for (i=0; i<narcs; ++i) { value a = Field(ml_arcs, i); arcs[i].x = Int_val(Field(a,0)); arcs[i].y = Int_val(Field(a,1)); arcs[i].width = UInt_val(Field(a,2)); arcs[i].height = UInt_val(Field(a,3)); arcs[i].angle1 = Int_val(Field(a,4)); arcs[i].angle2 = Int_val(Field(a,5)); } GET_STATUS XDrawArcs( Display_val(dpy), Drawable_val(d), GC_val(gc), arcs, narcs ); free(arcs); CHECK_STATUS(XDrawArcs,1); return Val_unit; } CAMLprim value ml_XDrawImageString( value dpy, value d, value gc, value x, value y, value str ) { GET_STATUS XDrawImageString( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), String_val(str), caml_string_length(str) ); CHECK_STATUS(XDrawImageString, 0); return Val_unit; } CAMLprim value ml_XDrawImageString_bytecode( value * argv, int argn ) { return ml_XDrawImageString( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_alloc_XChar2b( value b2 ) { CAMLparam1(b2); CAMLlocal1(xchar2b); XChar2b *char16; alloc_XChar2b(xchar2b); char16 = XChar2b_val(xchar2b); char16->byte1 = (unsigned char) Long_val(Field(b2,0)); char16->byte2 = (unsigned char) Long_val(Field(b2,1)); CAMLreturn(xchar2b); } CAMLprim value ml_alloc_XChar2b_string( value b2_string ) { CAMLparam1(b2_string); CAMLlocal2(ret, xchar2b_str); XChar2b *char16; long i, n; n = Wosize_val(b2_string); alloc_n_XChar2b(xchar2b_str, n); char16 = XChar2b_ptr_val(xchar2b_str); for (i=0; i < n; ++i) { value b2 = Field(b2_string, i); char16[i].byte1 = (unsigned char) Long_val(Field(b2,0)); char16[i].byte2 = (unsigned char) Long_val(Field(b2,1)); } ret = caml_alloc(2, 0); Store_field(ret, 0, xchar2b_str); Store_field(ret, 1, Val_long(n) ); CAMLreturn(ret); } CAMLprim value ml_XDrawImageString16( value dpy, value d, value gc, value x, value y, value xchar2b_string ) { GET_STATUS XDrawImageString16( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), XChar2b_string_val(xchar2b_string), XChar2b_string_length(xchar2b_string) ); CHECK_STATUS(XDrawImageString16,0); return Val_unit; } CAMLprim value ml_XDrawImageString16_bytecode( value * argv, int argn ) { return ml_XDrawImageString16( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XDrawLine( value dpy, value d, value gc, value x1, value y1, value x2, value y2 ) { GET_STATUS XDrawLine( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x1), Int_val(y1), Int_val(x2), Int_val(y2) ); CHECK_STATUS(XDrawLine,1); return Val_unit; } CAMLprim value ml_XDrawLine_bytecode( value * argv, int argn ) { return ml_XDrawLine( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } static const int coordinate_mode_table[] = { CoordModeOrigin, CoordModePrevious, }; CAMLprim value ml_XDrawLines( value dpy, value d, value gc, value ml_points, value ml_mode ) { int mode = coordinate_mode_table[ Long_val(ml_mode) ]; int i, npoints = Wosize_val(ml_points); XPoint * points = malloc(npoints * sizeof(XPoint)); for (i=0; i<npoints; ++i) { value pnt = Field(ml_points, i); points[i].x = Long_val(Field(pnt, 0)); points[i].y = Long_val(Field(pnt, 1)); } GET_STATUS XDrawLines( Display_val(dpy), Drawable_val(d), GC_val(gc), points, npoints, mode ); free(points); CHECK_STATUS(XDrawLines,1); return Val_unit; } CAMLprim value ml_XDrawPoint( value dpy, value d, value gc, value x, value y ) { GET_STATUS XDrawPoint( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y) ); CHECK_STATUS(XDrawPoint,1); return Val_unit; } CAMLprim value ml_XDrawPoints( value dpy, value d, value gc, value ml_points, value ml_mode ) { int mode = coordinate_mode_table[ Long_val(ml_mode) ]; int i, npoints = Wosize_val(ml_points); XPoint * points = malloc(npoints * sizeof(XPoint)); for (i=0; i<npoints; ++i) { value pnt = Field(ml_points, i); points[i].x = Long_val(Field(pnt, 0)); points[i].y = Long_val(Field(pnt, 1)); } GET_STATUS XDrawPoints( Display_val(dpy), Drawable_val(d), GC_val(gc), points, npoints, mode ); CHECK_STATUS(XDrawPoints,1); return Val_unit; } CAMLprim value ml_XDrawRectangle( value dpy, value d, value gc, value x, value y, value width, value height ) { GET_STATUS XDrawRectangle( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height) ); CHECK_STATUS(XDrawRectangle, 1); return Val_unit; } CAMLprim value ml_XDrawRectangle_bytecode( value * argv, int argn ) { return ml_XDrawRectangle( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_XDrawRectangles( value dpy, value d, value gc, value ml_rectangles ) { int i, nrectangles = Wosize_val(ml_rectangles); XRectangle * rectangles = malloc(nrectangles * sizeof(XRectangle)); for (i=0; i<nrectangles; ++i) { value rect = Field(ml_rectangles, i); rectangles[i].x = Int_val(Field(rect,0)); rectangles[i].y = Int_val(Field(rect,1)); rectangles[i].width = UInt_val(Field(rect,2)); rectangles[i].height = UInt_val(Field(rect,3)); } GET_STATUS XDrawRectangles( Display_val(dpy), Drawable_val(d), GC_val(gc), rectangles, nrectangles ); free(rectangles); CHECK_STATUS(XDrawRectangles,1); return Val_unit; } CAMLprim value ml_XDrawSegments( value dpy, value d, value gc, value ml_segments ) { XSegment* segments; int nsegments = Wosize_val(ml_segments); int i; segments = malloc(nsegments * sizeof(XSegment)); for (i=0; i<nsegments; ++i) { value seg = Field(ml_segments, i); segments[i].x1 = Int_val(Field(seg,0)); segments[i].y1 = Int_val(Field(seg,1)); segments[i].x2 = Int_val(Field(seg,2)); segments[i].y2 = Int_val(Field(seg,3)); } GET_STATUS XDrawSegments( Display_val(dpy), Drawable_val(d), GC_val(gc), segments, nsegments ); free(segments); CHECK_STATUS(XDrawSegments,1); return Val_unit; } CAMLprim value ml_XDrawString( value dpy, value d, value gc, value x, value y, value str ) { GET_STATUS XDrawString( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), String_val(str), caml_string_length(str) ); CHECK_STATUS(XDrawString, 0); return Val_unit; } CAMLprim value ml_XDrawString_bytecode( value * argv, int argn ) { return ml_XDrawString( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XDrawString16( value dpy, value d, value gc, value x, value y, value xchar2b_string ) { GET_STATUS XDrawString16( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), XChar2b_string_val(xchar2b_string), XChar2b_string_length(xchar2b_string) ); CHECK_STATUS(XDrawString16, 0); return Val_unit; } CAMLprim value ml_XDrawString16_bytecode( value * argv, int argn ) { return ml_XDrawString16( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } /* int XDrawText( Display* display, Drawable d, GC gc, int x, int y, XTextItem* items, int nitems ); int XDrawText16( Display* display, Drawable d, GC gc, int x, int y, XTextItem16* items, int nitems ); */ CAMLprim value ml_XFillArc( value dpy, value d, value gc, value x, value y, value width, value height, value angle1, value angle2 ) { GET_STATUS XFillArc( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), Int_val(angle1), Int_val(angle2) ); CHECK_STATUS(XFillArc, 1); return Val_unit; } CAMLprim value ml_XFillArc_bytecode( value * argv, int argn ) { return ml_XFillArc( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8] ); } CAMLprim value ml_XFillArcs( value dpy, value d, value gc, value ml_arcs ) { int i, narcs = Wosize_val(ml_arcs); XArc * arcs = malloc(narcs * sizeof(XArc)); for (i=0; i<narcs; ++i) { value a = Field(ml_arcs, i); arcs[i].x = Int_val(Field(a,0)); arcs[i].y = Int_val(Field(a,1)); arcs[i].width = UInt_val(Field(a,2)); arcs[i].height = UInt_val(Field(a,3)); arcs[i].angle1 = Int_val(Field(a,4)); arcs[i].angle2 = Int_val(Field(a,5)); } GET_STATUS XFillArcs( Display_val(dpy), Drawable_val(d), GC_val(gc), arcs, narcs ); free(arcs); CHECK_STATUS(XFillArcs,1); return Val_unit; } static const int shape_kind_table[] = { Complex, Nonconvex, Convex, }; CAMLprim value ml_XFillPolygon( value dpy, value d, value gc, value ml_points, value ml_shape, value ml_mode ) { int shape = shape_kind_table[ Long_val(ml_shape) ]; int mode = coordinate_mode_table[ Long_val(ml_mode) ]; int i, npoints = Wosize_val(ml_points); XPoint * points = malloc(npoints * sizeof(XPoint)); for (i=0; i<npoints; ++i) { value pnt = Field(ml_points, i); points[i].x = Long_val(Field(pnt, 0)); points[i].y = Long_val(Field(pnt, 1)); } GET_STATUS XFillPolygon( Display_val(dpy), Drawable_val(d), GC_val(gc), points, npoints, shape, mode ); free(points); CHECK_STATUS(XFillPolygon,1); return Val_unit; } CAMLprim value ml_XFillPolygon_bytecode( value * argv, int argn ) { return ml_XFillPolygon( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XFillRectangle( value dpy, value d, value gc, value x, value y, value width, value height ) { GET_STATUS XFillRectangle( Display_val(dpy), Drawable_val(d), GC_val(gc), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height) ); CHECK_STATUS(XFillRectangle, 1); return Val_unit; } CAMLprim value ml_XFillRectangle_bytecode( value * argv, int argn ) { return ml_XFillRectangle( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_XFillRectangles( value dpy, value d, value gc, value ml_rectangles ) { int i, nrectangles = Wosize_val(ml_rectangles); XRectangle * rectangles = malloc(nrectangles * sizeof(XRectangle)); for (i=0; i<nrectangles; ++i) { value rect = Field(ml_rectangles, i); rectangles[i].x = Int_val(Field(rect,0)); rectangles[i].y = Int_val(Field(rect,1)); rectangles[i].width = UInt_val(Field(rect,2)); rectangles[i].height = UInt_val(Field(rect,3)); } GET_STATUS XFillRectangles( Display_val(dpy), Drawable_val(d), GC_val(gc), rectangles, nrectangles ); free(rectangles); CHECK_STATUS(XFillRectangles,1); return Val_unit; } CAMLprim value ml_XCopyArea( value dpy, value src, value dest, value gc, value src_x, value src_y, value width, value height, value dest_x, value dest_y ) { GET_STATUS XCopyArea( Display_val(dpy), Drawable_val(src), Drawable_val(dest), GC_val(gc), Int_val(src_x), Int_val(src_y), UInt_val(width), UInt_val(height), Int_val(dest_x), Int_val(dest_y) ); CHECK_STATUS(XCopyArea,1); return Val_unit; } CAMLprim value ml_XCopyArea_bytecode( value * argv, int argn ) { return ml_XCopyArea( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9] ); } CAMLprim value ml_XCreatePixmap( value dpy, value dbl, value width, value height, value depth ) { Pixmap pixmap = XCreatePixmap( Display_val(dpy), Drawable_val(dbl), UInt_val(width), UInt_val(height), UInt_val(depth) ); return Val_Pixmap(pixmap); } CAMLprim value ml_XFreePixmap( value dpy, value pixmap ) { GET_STATUS XFreePixmap( Display_val(dpy), Pixmap_val(pixmap) ); CHECK_STATUS(XFreePixmap,1); return Val_unit; } CAMLprim value ml_XCreateBitmapFromData( value dpy, value dbl, value data, value width, value height ) { unsigned int _width = UInt_val(width); unsigned int _height = UInt_val(height); unsigned int len = caml_string_length(data); if (len < (_width * _height) / 8) { caml_invalid_argument("xCreateBitmapFromData"); } Pixmap pixmap = XCreateBitmapFromData( Display_val(dpy), Drawable_val(dbl), String_val(data), _width, _height ); return Val_Pixmap(pixmap); } CAMLprim value ml_XCreatePixmapCursor( value dpy, value source, value mask, value foreground, value background, value x, value y ) { Cursor cur = XCreatePixmapCursor( Display_val(dpy), Pixmap_val(source), Pixmap_val(mask), XColor_val(foreground), XColor_val(background), UInt_val(x), UInt_val(y) ); return Val_Cursor(cur); } CAMLprim value ml_XCreatePixmapCursor_bytecode( value * argv, int argn ) { return ml_XCreatePixmapCursor( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6] ); } CAMLprim value ml_XQueryBestTile( value dpy, value dbl, value width, value height ) { CAMLparam1(dpy); CAMLlocal1(size); unsigned int width_return, height_return; GET_STATUS XQueryBestTile( Display_val(dpy), Drawable_val(dbl), UInt_val(width), UInt_val(height), &width_return, &height_return ); CHECK_STATUS(XQueryBestTile,1); size = caml_alloc(2, 0); Store_field( size, 0, Val_uint(width_return) ); Store_field( size, 1, Val_uint(height_return) ); CAMLreturn(size); } CAMLprim value ml_XListPixmapFormats( value dpy ) { CAMLparam1(dpy); CAMLlocal2(arr, v); int i, count = 0; XPixmapFormatValues * pfv = NULL; pfv = XListPixmapFormats( Display_val(dpy), &count ); if (pfv == NULL) caml_failwith("xListPixmapFormats: out of memory"); arr = caml_alloc(count, 0); for (i=0; i<count; ++i) { v = caml_alloc(3, 0); Store_field(v, 0, Val_int(pfv[i].depth)); Store_field(v, 1, Val_int(pfv[i].bits_per_pixel)); Store_field(v, 2, Val_int(pfv[i].scanline_pad)); Store_field(arr, i, v); } XFree(pfv); CAMLreturn(arr); } /* XImage */ CAMLprim value ml_XImageByteOrder( value dpy ) { int order = _xImageByteOrder( Display_val(dpy) ); switch (order) { case LSBFirst: return Val_int(0); case MSBFirst: return Val_int(1); } caml_failwith("xImageByteOrder"); return Val_unit; } static const int ximage_format_table[] = { XYBitmap, XYPixmap, ZPixmap, }; #define XImage_format_val(i) (ximage_format_table[Long_val(i)]) #define Val_XImage(d) ((value)(d)) #define XImage_val(v) ((XImage *)(v)) CAMLprim value ml_XCreateImage( value dpy, value visual, value depth, value format, value offset, value data, value width, value height, value bitmap_pad, value bytes_per_line ) { char* _data; _data = (char *)((Tag_val(data) == String_tag)? (String_val(data)) : (Caml_ba_data_val(data))); XImage *ximage = XCreateImage( Display_val(dpy), Visual_val(visual), Int_val(depth), XImage_format_val(format), Int_val(offset), _data, UInt_val(width), UInt_val(height), Int_val(bitmap_pad), /* XXX */ Int_val(bytes_per_line) /* XXX */ ); return Val_XImage(ximage); } CAMLprim value ml_XCreateImage_bytecode( value * argv, int argn ) { return ml_XCreateImage( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9] ); } CAMLprim value ml_XDestroyImage( value ximage ) { //GET_STATUS XDestroyImage( XImage_val(ximage) ); //CHECK_STATUS(XDestroyImage,1); return Val_unit; } CAMLprim value ml_XSubImage( value ximage, value x, value y, value width, value height ) { XImage *sub_image = XSubImage( XImage_val(ximage), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height) ); return Val_XImage(sub_image); } CAMLprim value ml_XAllPlanes( value unit ) { return Val_ulong(XAllPlanes()); // TODO: maybe switch to an ocaml int32 } CAMLprim value ml_XGetImage( value dpy, value d, value x, value y, value width, value height, value plane_mask, value _format ) { XImage *ximage; int format = XImage_format_val(_format); if (format == XYBitmap) caml_invalid_argument("xGetImage: format should be XYPixmap or ZPixmap"); /* plane_mask represents an (unsigned long) and OCaml ints are C (long) and XAllPlanes() returns all bits set to 1 so even the signed bit. So we can not use the macro ULong_val() but Long_val() XXX: Maybe we should use an ocaml int32 ? */ ximage = XGetImage( Display_val(dpy), Drawable_val(d), Int_val(x), Int_val(y), UInt_val(width), UInt_val(height), ULong_val(plane_mask), // ULong_val(plane_mask), format ); if(ximage == NULL) { caml_failwith("XGetImage: xImage could not be created"); } return Val_XImage(ximage); } CAMLprim value ml_XGetImage_bytecode( value * argv, int argn ) { return ml_XGetImage( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7] ); } /* TODO: XImage *XGetSubImage( Display* display, Drawable d, int x, int y, unsigned int width, unsigned int height, unsigned long plane_mask, int format, XImage* dest_image, int dest_x, int dest_y ); */ CAMLprim value ml_XImage_data_str( value ximage ) { CAMLparam1(ximage); CAMLlocal1(ml_data); XImage *xim = XImage_val(ximage); unsigned long size = /* xim->width * */ xim->height * xim->bytes_per_line; void *data_ptr = (void*) (&(xim->data[0])); ml_data = caml_alloc_string(size); memcpy( String_val(ml_data), data_ptr, size ); CAMLreturn(ml_data); } CAMLprim value ml_XImage_data_ba( value ximage ) { CAMLparam1(ximage); CAMLlocal1(img_ba); XImage *xim = XImage_val(ximage); unsigned long size = /* xim->width * */ xim->height * xim->bytes_per_line; void *data_ptr = (void*) (&(xim->data[0])); long dims[3]; dims[0] = xim->width; dims[1] = xim->height; //dims[2] = xim->depth; /* TODO: DEBUG ME! */ dims[2] = xim->bytes_per_line / xim->width; img_ba = caml_ba_alloc(CAML_BA_UINT8 | CAML_BA_C_LAYOUT, 3, NULL, dims); memcpy( Caml_ba_data_val(img_ba), data_ptr, size ); CAMLreturn(img_ba); } CAMLprim value ml_XGetPixel( value ximage, value x, value y ) { unsigned long pixel = XGetPixel( XImage_val(ximage), Int_val(x), Int_val(y) ); return Val_pixel_color(pixel); } CAMLprim value ml_XPutPixel( value ximage, value x, value y, value pixel ) { //GET_STATUS XPutPixel( XImage_val(ximage), Int_val(x), Int_val(y), Pixel_color_val(pixel) ); //CHECK_STATUS(XPutPixel,1); return Val_unit; } CAMLprim value ml_XAddPixel( value ximage, value v ) { //GET_STATUS XAddPixel( XImage_val(ximage), Long_val(v) ); //CHECK_STATUS(XAddPixel,0); return Val_unit; } CAMLprim value ml_XPutImage( value dpy, value d, value gc, value ximage, value src_x, value src_y, value dest_x, value dest_y, value width, value height ) { //GET_STATUS XPutImage( Display_val(dpy), Drawable_val(d), GC_val(gc), XImage_val(ximage), Int_val(src_x), Int_val(src_y), Int_val(dest_x), Int_val(dest_y), UInt_val(width), UInt_val(height) ); //CHECK_STATUS(XPutImage,0); return Val_unit; } CAMLprim value ml_XPutImage_bytecode( value * argv, int argn ) { return ml_XPutImage( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9] ); } /* Font */ CAMLprim value ml_XLoadFont( value dpy, value name ) { Font font = XLoadFont( Display_val(dpy), String_val(name) ); return Val_Font(font); } /* Setting and Retrieving the Font Search Path */ CAMLprim value ml_XSetFontPath( value dpy, value ml_directories ) { char** directories; int ndirs, i; ndirs = Wosize_val(ml_directories); directories = malloc(ndirs * sizeof(char*)); for (i=0; i < ndirs; i++) { directories[i] = String_val(Field(ml_directories, i)); } GET_STATUS XSetFontPath( Display_val(dpy), directories, ndirs ); free(directories); CHECK_STATUS(XSetFontPath,1); return Val_unit; } CAMLprim value ml_XGetFontPath( value dpy ) { CAMLparam1( dpy ); CAMLlocal1(ml_paths); int npaths; char **paths = XGetFontPath( Display_val(dpy), &npaths ); ml_paths = caml_copy_string_array_n(paths, npaths); XFreeFontPath(paths); CAMLreturn( ml_paths ); } CAMLprim value ml_XListFonts( value dpy, value pattern, value maxnames ) { CAMLparam3( dpy, pattern, maxnames ); CAMLlocal1(ml_list); int actual_count; char **list = XListFonts( Display_val(dpy), String_val(pattern), Int_val(maxnames), &actual_count ); if (list == NULL) { caml_failwith("no matching font names"); } ml_list = caml_copy_string_array_n(list, actual_count); XFreeFontNames(list); CAMLreturn( ml_list ); } #if 0 TODO: char **XListFontsWithInfo( Display* /* display */, _Xconst char* /* pattern */, int /* maxnames */, int* /* count_return */, XFontStruct** /* info_return */ ); char **XListExtensions( Display* /* display */, int* /* nextensions_return */ ); #endif /* XEvent */ CAMLprim value ml_alloc_XEvent( value unit ) { CAMLparam0(); CAMLlocal1(event); alloc_XEvent(event); memset(XEvent_val(event), 0, sizeof(XEvent)); CAMLreturn(event); } CAMLprim value ml_XNextEvent( value dpy, value event ) { GET_STATUS XNextEvent( Display_val(dpy), XEvent_val(event) ); CHECK_STATUS(XNextEvent, 0); return Val_unit; } CAMLprim value ml_XPeekEvent( value dpy, value event ) { GET_STATUS XPeekEvent( Display_val(dpy), XEvent_val(event) ); CHECK_STATUS(XPeekEvent, 1); return Val_unit; } CAMLprim value ml_XNextEvent_fun( value dpy ) { CAMLparam1( dpy ); CAMLlocal1( ml_event ); XEvent event; GET_STATUS XNextEvent( Display_val(dpy), &event ); CHECK_STATUS(XNextEvent, 0); copy_XEvent( event, ml_event ); CAMLreturn( ml_event ); } CAMLprim value ml_XNextEvent_fun_2( value dpy ) // TODO test me { CAMLparam1(dpy); CAMLlocal1(event); alloc_XEvent(event); GET_STATUS XNextEvent( Display_val(dpy), XEvent_val(event) ); CHECK_STATUS(XNextEvent, 0); CAMLreturn(event); } CAMLprim value ml_XMaskEvent( value dpy, value event_mask_list, value event ) { long event_mask = Eventmask_val( event_mask_list ); GET_STATUS XMaskEvent( Display_val(dpy), event_mask, XEvent_val(event) ); CHECK_STATUS(XMaskEvent, 0); return Val_unit; } CAMLprim value ml_XWindowEvent( value dpy, value win, value event_mask_list ) { CAMLparam3( dpy, win, event_mask_list ); CAMLlocal1( event ); long event_mask = Eventmask_val( event_mask_list ); XEvent event_return; GET_STATUS XWindowEvent( Display_val(dpy), Window_val(win), event_mask, &event_return ); CHECK_STATUS(XWindowEvent, 0); copy_XEvent(event_return, event); CAMLreturn( event ); } CAMLprim value ml_XPending( value dpy ) { return Val_int(XPending( Display_val(dpy) )); } static const int event_mode_table[] = { AsyncPointer, SyncPointer, AsyncKeyboard, SyncKeyboard, ReplayPointer, ReplayKeyboard, AsyncBoth, SyncBoth, }; #define Event_mode_val(i) (event_mode_table[Long_val(i)]) CAMLprim value ml_XAllowEvents( value dpy, value event_mode, value time ) { //GET_STATUS XAllowEvents( Display_val(dpy), Event_mode_val(event_mode), Time_val(time) ); //CHECK_STATUS(XAllowEvents,1); return Val_unit; } CAMLprim value ml_XPutBackEvent( value dpy, value event ) { GET_STATUS XPutBackEvent( Display_val(dpy), XEvent_val(event) ); CHECK_STATUS(XPutBackEvent, 0); return Val_unit; } static const int event_type_table[] = { KeyPress, KeyRelease, ButtonPress, ButtonRelease, MotionNotify, EnterNotify, LeaveNotify, FocusIn, FocusOut, KeymapNotify, Expose, GraphicsExpose, NoExpose, VisibilityNotify, CreateNotify, DestroyNotify, UnmapNotify, MapNotify, MapRequest, ReparentNotify, ConfigureNotify, ConfigureRequest, GravityNotify, ResizeRequest, CirculateNotify, CirculateRequest, PropertyNotify, SelectionClear, SelectionRequest, SelectionNotify, ColormapNotify, ClientMessage, MappingNotify, }; CAMLprim value ml_XCheckTypedEvent( value dpy, value event_type, value event_return ) { if (XCheckTypedEvent( Display_val(dpy), event_type_table[Long_val(event_type)], XEvent_val(event_return) )) return Val_true; else return Val_false; } static const int queued_mode_table[] = { QueuedAlready, QueuedAfterFlush, QueuedAfterReading }; CAMLprim value ml_XEventsQueued( value dpy, value mode_i ) { int mode = queued_mode_table[Long_val(mode_i)]; int n = XEventsQueued( Display_val(dpy), mode ); return Val_int(n); } static inline value Val_event_type(int type) { switch (type) { case KeyPress: return Val_int(0); case KeyRelease: return Val_int(1); case ButtonPress: return Val_int(2); case ButtonRelease: return Val_int(3); case MotionNotify: return Val_int(4); case EnterNotify: return Val_int(5); case LeaveNotify: return Val_int(6); case FocusIn: return Val_int(7); case FocusOut: return Val_int(8); case KeymapNotify: return Val_int(9); case Expose: return Val_int(10); case GraphicsExpose: return Val_int(11); case NoExpose: return Val_int(12); case VisibilityNotify: return Val_int(13); case CreateNotify: return Val_int(14); case DestroyNotify: return Val_int(15); case UnmapNotify: return Val_int(16); case MapNotify: return Val_int(17); case MapRequest: return Val_int(18); case ReparentNotify: return Val_int(19); case ConfigureNotify: return Val_int(20); case ConfigureRequest: return Val_int(21); case GravityNotify: return Val_int(22); case ResizeRequest: return Val_int(23); case CirculateNotify: return Val_int(24); case CirculateRequest: return Val_int(25); case PropertyNotify: return Val_int(26); case SelectionClear: return Val_int(27); case SelectionRequest: return Val_int(28); case SelectionNotify: return Val_int(29); case ColormapNotify: return Val_int(30); case ClientMessage: return Val_int(31); case MappingNotify: return Val_int(32); default: caml_failwith("unhandled event type"); } return Val_unit; } CAMLprim value ml_XEvent_type( value event ) { return Val_event_type(XEvent_val(event)->type); } /* {{{ Get XEvents datas */ CAMLprim value ml_XAnyEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e = XEvent_val(event); dat = caml_alloc(5, 0); Store_field( dat, 0, Val_event_type(e->xany.type) ); Store_field( dat, 1, Val_ulong(e->xany.serial) ); Store_field( dat, 2, Val_bool(e->xany.send_event) ); Store_field( dat, 3, Val_Display(e->xany.display) ); Store_field( dat, 4, Val_Window(e->xany.window) ); CAMLreturn( dat ); } #define CHECK_EVENT_TYPE 1 // with 64 bit integers there's no need to check Time overflow anymore #define CHECK_TIME_OVERFLOW 0 static const unsigned int logical_state_mask_table[] = { AnyModifier, Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask, ShiftMask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask }; //define State_mask_val(i) (logical_state_mask_table[Long_val(i)]) static unsigned int State_mask_val(li) { int c_mask = 0; while ( li != Val_emptylist ) { value head = Field(li, 0); c_mask |= logical_state_mask_table[Long_val(head)]; li = Field(li, 1); } return c_mask; } #define Val_AnyModifier Val_int(0) #define Val_Button1Mask Val_int(1) #define Val_Button2Mask Val_int(2) #define Val_Button3Mask Val_int(3) #define Val_Button4Mask Val_int(4) #define Val_Button5Mask Val_int(5) #define Val_ShiftMask Val_int(6) #define Val_LockMask Val_int(7) #define Val_ControlMask Val_int(8) #define Val_Mod1Mask Val_int(9) #define Val_Mod2Mask Val_int(10) #define Val_Mod3Mask Val_int(11) #define Val_Mod4Mask Val_int(12) #define Val_Mod5Mask Val_int(13) static inline value Val_state_mask(unsigned int c_mask) { CAMLparam0(); CAMLlocal2(li, cons); li = Val_emptylist; #define push_mask(mask, Val_mask) \ if (c_mask & mask) { \ cons = caml_alloc(2, 0); \ Store_field(cons, 0, Val_mask); \ Store_field(cons, 1, li); \ li = cons; \ } push_mask( AnyModifier, Val_AnyModifier ) push_mask( Button1Mask, Val_Button1Mask ) push_mask( Button2Mask, Val_Button2Mask ) push_mask( Button3Mask, Val_Button3Mask ) push_mask( Button4Mask, Val_Button4Mask ) push_mask( Button5Mask, Val_Button5Mask ) push_mask( ShiftMask, Val_ShiftMask ) push_mask( LockMask, Val_LockMask ) push_mask( ControlMask, Val_ControlMask ) push_mask( Mod1Mask, Val_Mod1Mask ) push_mask( Mod2Mask, Val_Mod2Mask ) push_mask( Mod3Mask, Val_Mod3Mask ) push_mask( Mod4Mask, Val_Mod4Mask ) push_mask( Mod5Mask, Val_Mod5Mask ) CAMLreturn(li); } /* KeyPress / KeyRelease */ CAMLprim value ml_XKeyEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != KeyPress && e->type != KeyRelease) caml_invalid_argument("not a key event"); #endif #if CHECK_TIME_OVERFLOW if (e->xkey.time > MAX_INT64) caml_failwith("xKeyEvent_datas: time value overflow"); #endif dat = caml_alloc(14, 0); Store_field( dat, 0, Val_ulong(e->xkey.serial) ); Store_field( dat, 1, Val_bool(e->xkey.send_event) ); Store_field( dat, 2, Val_Display(e->xkey.display) ); Store_field( dat, 3, Val_Window(e->xkey.window) ); Store_field( dat, 4, Val_Window(e->xkey.root) ); Store_field( dat, 5, Val_Window(e->xkey.subwindow) ); Store_field( dat, 6, Val_time(e->xkey.time) ); Store_field( dat, 7, Val_int(e->xkey.x) ); Store_field( dat, 8, Val_int(e->xkey.y) ); Store_field( dat, 9, Val_int(e->xkey.x_root) ); Store_field( dat, 10, Val_int(e->xkey.y_root) ); Store_field( dat, 11, Val_state_mask(e->xkey.state) ); Store_field( dat, 12, Val_KeyCode(e->xkey.keycode) ); Store_field( dat, 13, Val_bool(e->xkey.same_screen) ); CAMLreturn( dat ); } #if 0 #define Val_Button1Mask Val_int(0) #define Val_Button2Mask Val_int(1) #define Val_Button3Mask Val_int(2) #define Val_Button4Mask Val_int(3) #define Val_Button5Mask Val_int(4) static inline value Val_button_mask( unsigned int state_mask ) { CAMLparam0(); CAMLlocal2(li, cons); li = Val_emptylist; if (state_mask & Button1Mask) { cons = caml_alloc(2, 0); Store_field( cons, 0, Val_Button1Mask ); Store_field( cons, 1, li ); li = cons; } if (state_mask & Button2Mask) { cons = caml_alloc(2, 0); Store_field( cons, 0, Val_Button2Mask ); Store_field( cons, 1, li ); li = cons; } if (state_mask & Button3Mask) { cons = caml_alloc(2, 0); Store_field( cons, 0, Val_Button3Mask ); Store_field( cons, 1, li ); li = cons; } if (state_mask & Button4Mask) { cons = caml_alloc(2, 0); Store_field( cons, 0, Val_Button4Mask ); Store_field( cons, 1, li ); li = cons; } if (state_mask & Button5Mask) { cons = caml_alloc(2, 0); Store_field( cons, 0, Val_Button5Mask ); Store_field( cons, 1, li ); li = cons; } CAMLreturn(li); } #endif /* MotionNotify */ CAMLprim value ml_XMotionEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != MotionNotify) caml_invalid_argument("not a MotionNotify event"); #endif #if CHECK_TIME_OVERFLOW if (e->xmotion.time > MAX_INT64) caml_failwith("xMotionEvent_datas: time value overflow"); #endif dat = caml_alloc(14, 0); Store_field( dat, 0, Val_ulong(e->xmotion.serial) ); Store_field( dat, 1, Val_bool(e->xmotion.send_event) ); Store_field( dat, 2, Val_Display(e->xmotion.display) ); Store_field( dat, 3, Val_Window(e->xmotion.window) ); Store_field( dat, 4, Val_Window(e->xmotion.root) ); Store_field( dat, 5, Val_Window(e->xmotion.subwindow) ); Store_field( dat, 6, Val_time(e->xmotion.time) ); Store_field( dat, 7, Val_int(e->xmotion.x) ); Store_field( dat, 8, Val_int(e->xmotion.y) ); Store_field( dat, 9, Val_int(e->xmotion.x_root) ); Store_field( dat, 10, Val_int(e->xmotion.y_root) ); Store_field( dat, 11, /*Val_button_mask*/Val_state_mask(e->xmotion.state) ); Store_field( dat, 12, Val_char(e->xmotion.is_hint) ); Store_field( dat, 13, Val_bool(e->xmotion.same_screen) ); CAMLreturn( dat ); } static const unsigned int button_table[] = { AnyButton, Button1, Button2, Button3, Button4, Button5, }; //unsigned int button = button_table[Long_val(v)]; #define Button_val(v) (button_table[Long_val(v)]) static inline value Val_button(unsigned int b) { switch (b) { case AnyButton: return Val_int(0); case Button1: return Val_int(1); case Button2: return Val_int(2); case Button3: return Val_int(3); case Button4: return Val_int(4); case Button5: return Val_int(5); } return Val_int(0); } /* ButtonPress / ButtonRelease */ CAMLprim value ml_XButtonEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ButtonPress && e->type != ButtonRelease) caml_invalid_argument("not a MotionNotify event"); #endif #if CHECK_TIME_OVERFLOW if (e->xmotion.time > MAX_INT64) caml_failwith("xButtonEvent_datas: time value overflow"); #endif dat = caml_alloc(14, 0); Store_field( dat, 0, Val_ulong(e->xbutton.serial) ); Store_field( dat, 1, Val_bool(e->xbutton.send_event) ); Store_field( dat, 2, Val_Display(e->xbutton.display) ); Store_field( dat, 3, Val_Window(e->xbutton.window) ); Store_field( dat, 4, Val_Window(e->xbutton.root) ); Store_field( dat, 5, Val_Window(e->xbutton.subwindow) ); Store_field( dat, 6, Val_time(e->xbutton.time) ); Store_field( dat, 7, Val_int(e->xbutton.x) ); Store_field( dat, 8, Val_int(e->xbutton.y) ); Store_field( dat, 9, Val_int(e->xbutton.x_root) ); Store_field( dat, 10, Val_int(e->xbutton.y_root) ); Store_field( dat, 11, Val_uint(e->xbutton.state) ); Store_field( dat, 12, Val_button(e->xbutton.button) ); Store_field( dat, 13, Val_bool(e->xbutton.same_screen) ); CAMLreturn( dat ); } static inline value Val_crossing_mode(int mode) { switch (mode) { case NotifyNormal : return Val_int(0); case NotifyGrab : return Val_int(1); case NotifyUngrab : return Val_int(2); } return Val_int(0); } static inline value Val_crossing_detail(int detail) { switch (detail) { case NotifyAncestor : return Val_int(0); case NotifyVirtual : return Val_int(1); case NotifyInferior : return Val_int(2); case NotifyNonlinear : return Val_int(3); case NotifyNonlinearVirtual : return Val_int(4); } return Val_int(0); } static inline value Val_crossing_state(int state) { switch (state) { case Button1Mask : return Val_int(0); case Button2Mask : return Val_int(1); case Button3Mask : return Val_int(2); case Button4Mask : return Val_int(3); case Button5Mask : return Val_int(4); case ShiftMask : return Val_int(5); case LockMask : return Val_int(6); case ControlMask : return Val_int(7); case Mod1Mask : return Val_int(8); case Mod2Mask : return Val_int(9); case Mod3Mask : return Val_int(10); case Mod4Mask : return Val_int(11); case Mod5Mask : return Val_int(12); } return Val_int(0); } /* EnterNotify / LeaveNotify */ CAMLprim value ml_XCrossingEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != EnterNotify && e->type != LeaveNotify) caml_invalid_argument("not a Crossing event"); #endif #if CHECK_TIME_OVERFLOW if (e->xcrossing.time > MAX_INT64) caml_failwith("xCrossingEvent_datas: time value overflow"); #endif dat = caml_alloc(13, 0); Store_field( dat, 0, Val_Window(e->xcrossing.window) ); Store_field( dat, 1, Val_Window(e->xcrossing.root) ); Store_field( dat, 2, Val_Window(e->xcrossing.subwindow) ); Store_field( dat, 3, Val_time(e->xcrossing.time) ); Store_field( dat, 4, Val_int(e->xcrossing.x) ); Store_field( dat, 5, Val_int(e->xcrossing.y) ); Store_field( dat, 6, Val_int(e->xcrossing.x_root) ); Store_field( dat, 7, Val_int(e->xcrossing.y_root) ); Store_field( dat, 8, Val_crossing_mode(e->xcrossing.mode) ); Store_field( dat, 9, Val_crossing_detail(e->xcrossing.detail) ); Store_field( dat, 10, Val_bool(e->xcrossing.same_screen) ); Store_field( dat, 11, Val_bool(e->xcrossing.focus) ); Store_field( dat, 12, Val_crossing_state(e->xcrossing.state) ); CAMLreturn( dat ); } static inline value Val_focus_mode(int n) { switch (n) { case NotifyNormal : return Val_int(0); case NotifyGrab : return Val_int(1); case NotifyUngrab : return Val_int(2); case NotifyWhileGrabbed: return Val_int(3); } return Val_int(0); } static inline value Val_focus_detail(int d) { switch (d) { case NotifyAncestor : return Val_int(0); case NotifyVirtual : return Val_int(1); case NotifyInferior : return Val_int(2); case NotifyNonlinear : return Val_int(3); case NotifyNonlinearVirtual: return Val_int(4); case NotifyPointer : return Val_int(5); case NotifyPointerRoot : return Val_int(6); case NotifyDetailNone : return Val_int(7); } return Val_int(0); } /* FocusIn / FocusOut */ CAMLprim value ml_XFocusChangeEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != FocusIn && e->type != FocusOut) caml_invalid_argument("not a FocusChange event"); #endif dat = caml_alloc(2, 0); Store_field( dat, 0, Val_focus_mode(e->xfocus.mode) ); Store_field( dat, 1, Val_focus_detail(e->xfocus.detail) ); CAMLreturn( dat ); } /* KeymapNotify */ CAMLprim value ml_XKeymapEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal2( dat, key_str ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != KeymapNotify) caml_invalid_argument("not a KeymapNotify event"); #endif key_str = caml_alloc_string (32); memcpy( String_val(key_str), (e->xkeymap.key_vector), 32 ); dat = caml_alloc(1, 0); Store_field( dat, 0, key_str ); CAMLreturn( dat ); } /* Expose */ CAMLprim value ml_XExposeEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != Expose) caml_invalid_argument("not an Expose event"); #endif dat = caml_alloc(5, 0); Store_field( dat, 0, Val_int(e->xexpose.x) ); Store_field( dat, 1, Val_int(e->xexpose.y) ); Store_field( dat, 2, Val_int(e->xexpose.width) ); Store_field( dat, 3, Val_int(e->xexpose.height) ); Store_field( dat, 4, Val_int(e->xexpose.count) ); CAMLreturn( dat ); } /* TODO GraphicsExpose TODO NoExpose */ static inline value Val_visibility_state(int v) { switch (v) { case VisibilityUnobscured : return Val_int(0); case VisibilityPartiallyObscured: return Val_int(1); case VisibilityFullyObscured : return Val_int(2); } return Val_int(0); } /* VisibilityNotify */ CAMLprim value ml_XVisibilityEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != VisibilityNotify) caml_invalid_argument("not a VisibilityNotify event"); #endif dat = caml_alloc(1, 0); Store_field( dat, 0, Val_visibility_state(e->xvisibility.state) ); CAMLreturn( dat ); } /* CreateNotify */ CAMLprim value ml_XCreateWindowEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e = XEvent_val(event); dat = caml_alloc(11, 0); Store_field( dat, 0, Val_ulong(e->xcreatewindow.serial) ); Store_field( dat, 1, Val_bool(e->xcreatewindow.send_event) ); Store_field( dat, 2, Val_Display(e->xcreatewindow.display) ); Store_field( dat, 3, Val_Window(e->xcreatewindow.parent) ); Store_field( dat, 4, Val_Window(e->xcreatewindow.window) ); Store_field( dat, 5, Val_int(e->xcreatewindow.x) ); Store_field( dat, 6, Val_int(e->xcreatewindow.y) ); Store_field( dat, 7, Val_int(e->xcreatewindow.width) ); Store_field( dat, 8, Val_int(e->xcreatewindow.height) ); Store_field( dat, 9, Val_int(e->xcreatewindow.border_width) ); Store_field( dat, 10, Val_bool(e->xcreatewindow.override_redirect) ); CAMLreturn( dat ); } /* DestroyNotify */ CAMLprim value ml_XDestroyWindowEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != DestroyNotify) caml_invalid_argument("not a DestroyNotify event"); #endif dat = caml_alloc(2, 0); Store_field( dat, 0, Val_Window(e->xdestroywindow.event) ); Store_field( dat, 1, Val_Window(e->xdestroywindow.window) ); CAMLreturn( dat ); } /* TODO UnmapNotify TODO MapNotify TODO MapRequest */ /* ReparentNotify */ CAMLprim value ml_XReparentEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ReparentNotify) caml_invalid_argument("not a ReparentNotify event"); #endif dat = caml_alloc(2, 0); Store_field( dat, 0, Val_Window(e->xreparent.event) ); Store_field( dat, 1, Val_Window(e->xreparent.window) ); Store_field( dat, 2, Val_Window(e->xreparent.parent) ); Store_field( dat, 3, Val_int(e->xreparent.x) ); Store_field( dat, 4, Val_int(e->xreparent.y) ); Store_field( dat, 5, Val_bool(e->xreparent.override_redirect) ); CAMLreturn( dat ); } /* ConfigureNotify */ CAMLprim value ml_XConfigureEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ConfigureNotify) caml_invalid_argument("not a ConfigureNotify event"); #endif dat = caml_alloc(7, 0); Store_field( dat, 0, Val_int(e->xconfigure.x) ); Store_field( dat, 1, Val_int(e->xconfigure.y) ); Store_field( dat, 2, Val_int(e->xconfigure.width) ); Store_field( dat, 3, Val_int(e->xconfigure.height) ); Store_field( dat, 4, Val_int(e->xconfigure.border_width) ); Store_field( dat, 5, Val_Window(e->xconfigure.above) ); Store_field( dat, 6, Val_bool(e->xconfigure.override_redirect) ); CAMLreturn( dat ); } /* ConfigureRequest */ static inline value Val_xconfreq_detail(int detail) { switch (detail) { case Above : return Val_int(0); case Below : return Val_int(1); case TopIf : return Val_int(2); case BottomIf : return Val_int(3); case Opposite : return Val_int(4); } return Val_int(0); } CAMLprim value ml_XConfigureRequestEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ConfigureRequest) caml_invalid_argument("not a ConfigureRequest event"); #endif dat = caml_alloc(10, 0); Store_field( dat, 0, Val_Window(e->xconfigurerequest.parent) ); Store_field( dat, 1, Val_Window(e->xconfigurerequest.window) ); Store_field( dat, 2, Val_int(e->xconfigurerequest.x) ); Store_field( dat, 3, Val_int(e->xconfigurerequest.y) ); Store_field( dat, 4, Val_int(e->xconfigurerequest.width) ); Store_field( dat, 5, Val_int(e->xconfigurerequest.height) ); Store_field( dat, 6, Val_int(e->xconfigurerequest.border_width) ); Store_field( dat, 7, Val_Window(e->xconfigurerequest.above) ); Store_field( dat, 8, Val_xconfreq_detail(e->xconfigurerequest.detail) ); Store_field( dat, 9, Val_ulong(e->xconfigurerequest.value_mask) ); /* TODO */ CAMLreturn( dat ); } /* TODO GravityNotify */ /* ResizeRequest */ CAMLprim value ml_XResizeRequestEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ResizeRequest) caml_invalid_argument("not a ResizeRequest event"); #endif dat = caml_alloc(2, 0); Store_field( dat, 0, Val_int(e->xresizerequest.width) ); Store_field( dat, 1, Val_int(e->xresizerequest.height) ); CAMLreturn( dat ); } /* TODO CirculateNotify TODO CirculateRequest TODO PropertyNotify TODO SelectionClear TODO SelectionRequest */ CAMLprim value Val_Atom_option( Atom a ) { if (a == None) return Val_none; else return Val_some( Val_Atom(a) ); } /* SelectionNotify */ CAMLprim value ml_XSelectionEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != SelectionNotify) caml_invalid_argument("not a SelectionNotify event"); #endif #if CHECK_TIME_OVERFLOW if (e->xselection.time > MAX_INT64) caml_failwith("xSelectionEvent_datas: time value overflow"); #endif dat = caml_alloc(5, 0); Store_field( dat, 0, Val_Window(e->xselection.requestor) ); Store_field( dat, 1, Val_Atom(e->xselection.selection) ); Store_field( dat, 2, Val_Atom(e->xselection.target) ); Store_field( dat, 3, Val_Atom_option(e->xselection.property) ); /* Atom or None */ Store_field( dat, 4, Val_time(e->xselection.time) ); CAMLreturn( dat ); } /* TODO ColormapNotify TODO ClientMessage TODO MappingNotify */ /* XErrorEvent */ CAMLprim value ml_XErrorEvent_datas( value event ) { CAMLparam1( event ); CAMLlocal1( dat ); XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE /* // don't know how is set this field for the XerrorEvent if (e->type != ??? ) caml_invalid_argument("not an error event"); */ #endif #if CHECK_TIME_OVERFLOW if (e->xkey.time > MAX_INT64) caml_failwith("xKeyEvent_datas: time value overflow"); #endif dat = caml_alloc(6, 0); Store_field( dat, 0, Val_Display(e->xerror.display) ); Store_field( dat, 1, Val_XID(e->xerror.resourceid ) ); Store_field( dat, 2, Val_ulong(e->xerror.serial ) ); Store_field( dat, 3, Val_char(e->xerror.error_code ) ); Store_field( dat, 4, Val_char(e->xerror.request_code ) ); Store_field( dat, 5, Val_char(e->xerror.minor_code ) ); CAMLreturn( dat ); } /* }}} */ CAMLprim value ml_XSendEvent( value dpy, value win, value propagate, value event_mask, value event_content ) { XEvent ev; value cont = Field(event_content,0); switch (Tag_val(event_content)) { case 0: // {{{ XMotionEvCnt ev.type = MotionNotify; ev.xmotion.serial = ULong_val(Field(cont, 0)); ev.xmotion.send_event = Bool_val(Field(cont, 1)); ev.xmotion.display = Display_val(Field(cont, 2)); ev.xmotion.window = Window_val(Field(cont, 3)); ev.xmotion.root = Window_val(Field(cont, 4)); ev.xmotion.subwindow = Window_val(Field(cont, 5)); ev.xmotion.time = Time_val(Field(cont, 6)); ev.xmotion.x = Int_val(Field(cont, 7)); ev.xmotion.y = Int_val(Field(cont, 8)); ev.xmotion.x_root = Int_val(Field(cont, 9)); ev.xmotion.y_root = Int_val(Field(cont, 10)); ev.xmotion.state = State_mask_val(Field(cont, 11)); ev.xmotion.is_hint = Char_val(Field(cont, 12)); ev.xmotion.same_screen = Bool_val(Field(cont, 13)); break; // }}} case 1: // {{{ XKeyPressedEvCnt ev.type = KeyPress; ev.xkey.serial = ULong_val(Field(cont, 0)); ev.xkey.send_event = Bool_val(Field(cont, 1)); ev.xkey.display = Display_val(Field(cont, 2)); ev.xkey.window = Window_val(Field(cont, 3)); ev.xkey.root = Window_val(Field(cont, 4)); ev.xkey.subwindow = Window_val(Field(cont, 5)); ev.xkey.time = Time_val(Field(cont, 6)); ev.xkey.x = Int_val(Field(cont, 7)); ev.xkey.y = Int_val(Field(cont, 8)); ev.xkey.x_root = Int_val(Field(cont, 9)); ev.xkey.y_root = Int_val(Field(cont, 10)); ev.xkey.state = State_mask_val(Field(cont, 11)); ev.xkey.keycode = KeyCode_val(Field(cont, 12)); ev.xkey.same_screen = Bool_val(Field(cont, 13)); break; // }}} case 2: // {{{ XKeyReleasedEvCnt ev.type = KeyRelease; ev.xkey.serial = ULong_val(Field(cont, 0)); ev.xkey.send_event = Bool_val(Field(cont, 1)); ev.xkey.display = Display_val(Field(cont, 2)); ev.xkey.window = Window_val(Field(cont, 3)); ev.xkey.root = Window_val(Field(cont, 4)); ev.xkey.subwindow = Window_val(Field(cont, 5)); ev.xkey.time = Time_val(Field(cont, 6)); ev.xkey.x = Int_val(Field(cont, 7)); ev.xkey.y = Int_val(Field(cont, 8)); ev.xkey.x_root = Int_val(Field(cont, 9)); ev.xkey.y_root = Int_val(Field(cont, 10)); ev.xkey.state = State_mask_val(Field(cont, 11)); ev.xkey.keycode = KeyCode_val(Field(cont, 12)); ev.xkey.same_screen = Bool_val(Field(cont, 13)); break; // }}} case 3: // {{{ XButtonPressedEvCnt ev.type = ButtonPress; ev.xbutton.serial = ULong_val(Field(cont, 0)); ev.xbutton.send_event = Bool_val(Field(cont, 1)); ev.xbutton.display = Display_val(Field(cont, 2)); ev.xbutton.window = Window_val(Field(cont, 3)); ev.xbutton.root = Window_val(Field(cont, 4)); ev.xbutton.subwindow = Window_val(Field(cont, 5)); ev.xbutton.time = Time_val(Field(cont, 6)); ev.xbutton.x = Int_val(Field(cont, 7)); ev.xbutton.y = Int_val(Field(cont, 8)); ev.xbutton.x_root = Int_val(Field(cont, 9)); ev.xbutton.y_root = Int_val(Field(cont, 10)); ev.xbutton.state = UInt_val(Field(cont, 11)); ev.xbutton.button = Button_val(Field(cont, 12)); ev.xbutton.same_screen = Bool_val(Field(cont, 13)); break; // }}} case 4: // {{{ XButtonReleasedEvCnt ev.type = ButtonRelease; ev.xbutton.serial = ULong_val(Field(cont, 0)); ev.xbutton.send_event = Bool_val(Field(cont, 1)); ev.xbutton.display = Display_val(Field(cont, 2)); ev.xbutton.window = Window_val(Field(cont, 3)); ev.xbutton.root = Window_val(Field(cont, 4)); ev.xbutton.subwindow = Window_val(Field(cont, 5)); ev.xbutton.time = Time_val(Field(cont, 6)); ev.xbutton.x = Int_val(Field(cont, 7)); ev.xbutton.y = Int_val(Field(cont, 8)); ev.xbutton.x_root = Int_val(Field(cont, 9)); ev.xbutton.y_root = Int_val(Field(cont, 10)); ev.xbutton.state = UInt_val(Field(cont, 11)); ev.xbutton.button = Button_val(Field(cont, 12)); ev.xbutton.same_screen = Bool_val(Field(cont, 13)); break; // }}} case 5: // XCrossingEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 6: // XFocusChangeEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 7: // XKeymapEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 8: // XExposeEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 9: // XGraphicsExposeEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 10: // XNoExposeEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 11: // XVisibilityEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 12: // XCreateWindowEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 13: // XDestroyWindowEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 14: // XUnmapEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 15: // XMapEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 16: // XMapRequestEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 17: // XReparentEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 18: // XConfigureEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 19: // XConfigureRequestEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 20: // XGravityEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 21: // XResizeRequestEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 22: // XCirculateEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 23: // XCirculateRequestEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 24: // XPropertyEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 25: // XSelectionClearEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 26: // XSelectionRequestEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 27: // XSelectionEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 28: // XColormapEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; case 29: // XClientMessageEvCnt ev.type = ClientMessage; ev.xclient.serial = ULong_val(Field(cont, 0)); ev.xclient.send_event = Bool_val(Field(cont, 1)); ev.xclient.display = Display_val(Field(cont, 2)); ev.xclient.window = Window_val(Field(cont, 3)); ev.xclient.message_type = Atom_val(Field(cont, 4)); value data = Field(cont, 5); value array = Field(data, 0); int len; int actual_len = Wosize_val(array); switch(Tag_val(data)) { case 0: // bytes ev.xclient.format = 8; len = 20; if(len != actual_len) caml_failwith("xClientMessgeEvent_data expected an array of 20"); while(--len >=0) { char val = (char)Int_val(Field(array, len)); ev.xclient.data.b[len] = val; } break; case 1: // shorts ev.xclient.format = 16; len = 10; if(len != actual_len) caml_failwith("xClientMessgeEvent_data expected an array of 10"); while(--len >=0) { short val = (short)Int_val(Field(array, len)); ev.xclient.data.s[len] = val; } break; case 2: // longs ev.xclient.format = 32; len = 5; if(len != actual_len) caml_failwith("xClientMessgeEvent_data expected an array of 5"); while(--len >=0) { long val = Int_val(Field(array, len)); ev.xclient.data.l[len] = val; } break; default: caml_failwith("xClientMessgeEvent_data unknown type"); } break; case 30: // XMappingEvCnt caml_failwith("xSendEvent TODO: this event_content is not handled yet"); break; default: caml_failwith("variant handling bug"); } Status st = XSendEvent( Display_val(dpy), Window_val(win), Bool_val(propagate), event_mask_table[Long_val(event_mask)], &ev ); if (st == 0) { caml_failwith("xSendEvent: failed"); } return Val_unit; } CAMLprim value ml_XEvent_xclient_data_l_0( value event ) { XEvent * e; e = XEvent_val(event); #if CHECK_EVENT_TYPE // The type inference should garanty this: if (e->type != ClientMessage) caml_invalid_argument("not a ClientMessage event"); #endif long atom = e->xclient.data.l[0]; return Val_Atom( atom ); } /* int XLookupString( XKeyEvent* event_struct, char* buffer_return, int bytes_buffer, KeySym* keysym_return, XComposeStatus* status_in_out ); */ #if 0 #include <X11/keysym.h> CAMLprim value _ml_XLookupString( value event ) { XEvent * e; KeySym keysym; e = XEvent_val(event); XComposeStatus* status_in_out = NULL; char buffer_txt[256]; char * p; int nchar; nchar = XLookupString( &(e->xkey), buffer_txt, sizeof(buffer_txt), &keysym, status_in_out ); for (p = buffer_txt; nchar > 0; ++p, --nchar) printf("%c", *p); printf("\n"); fflush(stdout); switch (keysym) { #define KEY_CASE(k) case k: printf(#k "\n"); break; // {{{ KEY_CASE(<KEY>) KEY_CASE(XK_F1) KEY_CASE(XK_a) KEY_CASE(XK_b) KEY_CASE(XK_c) KEY_CASE(XK_d) KEY_CASE(XK_e) KEY_CASE(XK_f) KEY_CASE(XK_g) KEY_CASE(XK_h) KEY_CASE(XK_i) KEY_CASE(XK_j) KEY_CASE(XK_A) KEY_CASE(XK_B) KEY_CASE(XK_C) KEY_CASE(XK_D) KEY_CASE(XK_E) KEY_CASE(XK_F) KEY_CASE(XK_G) // }}} #undef KEY_CASE } return Val_unit; } #endif CAMLprim value ml_XLookupString( value event, value buffer ) { CAMLparam1( event ); CAMLlocal1( ret ); KeySym keysym; XEvent * e = XEvent_val(event); #if CHECK_EVENT_TYPE if (e->type != KeyPress && e->type != KeyRelease) caml_invalid_argument("not a key event"); #endif // XComposeStatus stat; int nchars = XLookupString( // from <X11/Xutil.h> &(e->xkey), String_val(buffer), caml_string_length(buffer), &keysym, NULL /* &stat */ ); ret = caml_alloc(2, 0); Store_field( ret, 0, Val_int(nchars) ); Store_field( ret, 1, Val_keysym(keysym) ); CAMLreturn( ret ); } // TODO: Xutf8LookupString, XwcLookupString, XmbLookupString CAMLprim value ml_XLookupKeysym( value event, value index ) { XEvent * e = XEvent_val(event); #if CHECK_EVENT_TYPE if (e->type != KeyPress && e->type != KeyRelease) caml_invalid_argument("not a key event"); #endif KeySym keysym = XLookupKeysym( &(e->xkey), Int_val(index) ); // index from 0 to (keysyms_per_keycode - 1) return Val_keysym(keysym); } CAMLprim value ml_XRefreshKeyboardMapping( value event ) { XEvent *e; e = XEvent_val(event); #if CHECK_EVENT_TYPE if (e->type != MappingNotify) caml_invalid_argument("not a MappingNotify event"); #endif XRefreshKeyboardMapping(&(e->xmapping)); return Val_unit; } CAMLprim value ml_XDisplayKeycodes( value dpy ) { CAMLparam1( dpy ); CAMLlocal1( tpl ); int min_keycodes, max_keycodes; //GET_STATUS XDisplayKeycodes( Display_val(dpy), &min_keycodes, &max_keycodes ); //CHECK_STATUS(XDisplayKeycodes,1); tpl = caml_alloc(2, 0); Store_field( tpl, 0, Val_KeyCode(min_keycodes) ); Store_field( tpl, 1, Val_KeyCode(max_keycodes) ); CAMLreturn( tpl ); } /* TODO: //GET_STATUS XRebindKeysym( Display_val(dpy), KeySym keysym, KeySym* list, int mod_count, _Xconst unsigned char* string, int bytes_string ); //CHECK_STATUS(XRebindKeysym,0); http://tronche.com/gui/x/xlib/utilities/XRebindKeysym.html */ CAMLprim value ml_XGetKeyboardMapping( value dpy, value first_keycode, value ml_keycode_count ) { CAMLparam3(dpy, first_keycode, ml_keycode_count); CAMLlocal2(ml_keysyms, sub); int keysyms_per_keycode; KeySym *keysyms; //unsigned int keysyms_len; int i, j; int keycode_count = Int_val(ml_keycode_count); { int min_keycode, max_keycode; XDisplayKeycodes( Display_val(dpy), &min_keycode, &max_keycode ); if (Long_val(first_keycode) < min_keycode) caml_invalid_argument("xGetKeyboardMapping: " "first_keycode must be greater than or equal to min_keycode"); } keysyms = XGetKeyboardMapping( Display_val(dpy), KeyCode_val(first_keycode), keycode_count, &keysyms_per_keycode ); // number of elements in the KeySyms list //keysyms_len = (keycode_count * keysyms_per_keycode); ml_keysyms = caml_alloc(keycode_count, 0); printf("keysyms_per_keycode = %d\n", keysyms_per_keycode); // XXX DEBUG XXX for (i=0; i < keycode_count; ++i) { int n = 0; for (j=0; j < keysyms_per_keycode; ++j) { // don't return undefined keysyms if (keysyms[keysyms_per_keycode + i + j] != NoSymbol) n++; } sub = caml_alloc(n, 0); for (j=0; j < n; ++j) { Store_field(sub, j, Val_keysym( keysyms[keysyms_per_keycode + i + j] ) ); } Store_field(ml_keysyms, i, sub); } XFree(keysyms); CAMLreturn( ml_keysyms ); } // http://tronche.com/gui/x/xlib/input/XGetKeyboardMapping.html /* TODO: KeySym keysym = XStringToKeysym( char* string ); */ CAMLprim value ml_XChangeKeyboardMapping( // ---------------- WIP value dpy, value first_keycode, value keysyms_per_keycode, value keysyms_arr, value num_codes ) { KeySym* keysyms; int i, keysyms_len; int keysyms_len_should; keysyms_len = Wosize_val(keysyms_arr); keysyms_len_should = Int_val(num_codes) * Int_val(keysyms_per_keycode); if (keysyms_len != keysyms_len_should) { caml_invalid_argument("xChangeKeyboardMapping: " "keysyms array should contain " "(num_codes * keysyms_per_keycode) elements"); } /* From the man: http://tronche.com/gui/x/xlib/input/XChangeKeyboardMapping.html The specified first_keycode must be greater than or equal to min_keycode returned by XDisplayKeycodes(), or a BadValue error results. In addition, the following expression must be less than or equal to max_keycode, or a BadValue error results: (first_keycode + num_codes - 1) TODO: handle this BadValue error */ { int min_keycode, max_keycode; XDisplayKeycodes( Display_val(dpy), &min_keycode, &max_keycode ); if (Long_val(first_keycode) < min_keycode) { caml_invalid_argument("xChangeKeyboardMapping: " "first_keycode must be greater than or equal to min_keycode"); } if ((Long_val(first_keycode) + Int_val(num_codes) - 1) > max_keycode) { caml_invalid_argument("xChangeKeyboardMapping: " "(first_keycode + num_codes - 1) must be less than or equal to max_keycode"); } } keysyms = malloc(keysyms_len * sizeof(KeySym)); for (i=0; i < keysyms_len; ++i) { keysyms[i] = Keysym_val(Field(keysyms_arr, i)); } //GET_STATUS XChangeKeyboardMapping( Display_val(dpy), KeyCode_val(first_keycode), Int_val(keysyms_per_keycode), keysyms, Int_val(num_codes) ); free(keysyms); //CHECK_STATUS(XChangeKeyboardMapping,0); return Val_unit; } CAMLprim value ml_XChangeKeyboardMapping_single( value dpy, value first_keycode, value keysym ) { KeySym keysyms[1]; keysyms[0] = Keysym_val(keysym); //GET_STATUS XChangeKeyboardMapping( Display_val(dpy), KeyCode_val(first_keycode), 1, keysyms, 1 ); //CHECK_STATUS(XChangeKeyboardMapping,0); return Val_unit; } /* Keyboard */ CAMLprim value ml_XAutoRepeatOff( value dpy ) { GET_STATUS XAutoRepeatOff( Display_val(dpy) ); CHECK_STATUS(XAutoRepeatOff,1); return Val_unit; } CAMLprim value ml_XAutoRepeatOn( value dpy ) { GET_STATUS XAutoRepeatOn( Display_val(dpy) ); CHECK_STATUS(XAutoRepeatOn,1); return Val_unit; } CAMLprim value ml_XQueryKeymap( value dpy ) { CAMLparam1( dpy ); CAMLlocal1( ml_keys ); ml_keys = caml_alloc_string(32); char *keys_ptr; keys_ptr = String_val(ml_keys); GET_STATUS XQueryKeymap( Display_val(dpy), keys_ptr ); CHECK_STATUS(XQueryKeymap,1); CAMLreturn( ml_keys ); } CAMLprim value ml_XQueryPointer( value dpy, value win ) { CAMLparam2( dpy, win ); CAMLlocal2( pntr, subp ); Window root, child; int root_x, root_y, win_x, win_y; unsigned int mask; Bool b = XQueryPointer( Display_val(dpy), Window_val(win), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask ); pntr = caml_alloc(5, 0); if (b) { subp = caml_alloc(3, 0); Store_field( subp, 0, Val_Window(child) ); Store_field( subp, 1, Val_int(win_x) ); Store_field( subp, 2, Val_int(win_y) ); Store_field( pntr, 0, Val_Window(root) ); Store_field( pntr, 1, Val_int(root_x) ); Store_field( pntr, 2, Val_int(root_y) ); Store_field( pntr, 3, Val_some( subp ) ); Store_field( pntr, 4, Val_state_mask(mask) ); } else { Store_field( pntr, 0, Val_Window(root) ); Store_field( pntr, 1, Val_int(root_x) ); Store_field( pntr, 2, Val_int(root_y) ); Store_field( pntr, 3, Val_none ); Store_field( pntr, 4, Val_state_mask(mask) ); } CAMLreturn( pntr ); } CAMLprim value ml_XGetKeyboardControl( value dpy ) { CAMLparam1( dpy ); CAMLlocal2( tpl, ml_auto_repeats ); XKeyboardState kbs; GET_STATUS XGetKeyboardControl( Display_val(dpy), &kbs ); CHECK_STATUS(XGetKeyboardControl,1); tpl = caml_alloc(7, 0); ml_auto_repeats = caml_alloc_string(32); memcpy(String_val(ml_auto_repeats), kbs.auto_repeats, 32); Store_field( tpl, 0, Val_int(kbs.key_click_percent) ); Store_field( tpl, 1, Val_int(kbs.bell_percent) ); Store_field( tpl, 2, Val_uint(kbs.bell_pitch) ); Store_field( tpl, 3, Val_uint(kbs.bell_duration) ); Store_field( tpl, 4, Val_ulong(kbs.led_mask) ); // TODO: WRAP ME Store_field( tpl, 5, Val_int( (kbs.global_auto_repeat == AutoRepeatModeOff ? 0 : 1)) ); Store_field( tpl, 6, ml_auto_repeats ); CAMLreturn( tpl ); } #if 0 static const unsigned int keyboardcontrol_table[] = { KBKeyClickPercent, KBBellPercent, KBBellPitch, KBBellDuration, KBLed, KBLedMode, KBKey, KBAutoRepeatMode, }; #define keyboardcontrol_mask_val(i) (keyboardcontrol_table[Long_val(i)]) /* TODO if (mask & KBKeyClickPercent) *value++ = value_list->key_click_percent; if (mask & KBBellPercent) *value++ = value_list->bell_percent; if (mask & KBBellPitch) *value++ = value_list->bell_pitch; if (mask & KBBellDuration) *value++ = value_list->bell_duration; if (mask & KBLed) *value++ = value_list->led; if (mask & KBLedMode) *value++ = value_list->led_mode; if (mask & KBKey) *value++ = value_list->key; if (mask & KBAutoRepeatMode) *value++ = value_list->auto_repeat_mode; typedef struct { int key_click_percent; int bell_percent; int bell_pitch; int bell_duration; int led; int led_mode; int key; int auto_repeat_mode; // On, Off, Default } XKeyboardControl; */ CAMLprim value ml_XChangeKeyboardControl( value dpy, value ml_xkeyboardcontrol_tpl ) { unsigned long value_mask; while ( em_list != Val_emptylist ) { value head = Field(em_list, 0); long mask = keyboardcontrol_mask_val(head); value_mask |= mask; em_list = Field(em_list, 1); } //GET_STATUS XChangeKeyboardControl( Display_val(dpy), value_mask, XKeyboardControl* values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } #endif CAMLprim value ml_XChangeKeyboardControl_bell_percent( value dpy, value ml_bell_percent ) { XKeyboardControl keyboard_control_values; keyboard_control_values.bell_percent = Int_val(ml_bell_percent); //GET_STATUS XChangeKeyboardControl( Display_val(dpy), KBBellPercent, &keyboard_control_values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } CAMLprim value ml_XChangeKeyboardControl_bell_pitch( value dpy, value ml_bell_pitch ) { XKeyboardControl keyboard_control_values; keyboard_control_values.bell_pitch = Int_val(ml_bell_pitch); //GET_STATUS XChangeKeyboardControl( Display_val(dpy), KBBellPitch, &keyboard_control_values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } CAMLprim value ml_XChangeKeyboardControl_bell_duration( value dpy, value ml_bell_duration ) { XKeyboardControl keyboard_control_values; keyboard_control_values.bell_duration = Int_val(ml_bell_duration); //GET_STATUS XChangeKeyboardControl( Display_val(dpy), KBBellDuration, &keyboard_control_values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } CAMLprim value ml_XChangeKeyboardControl_bell( value dpy, value ml_bell_percent, value ml_bell_pitch, value ml_bell_duration ) { XKeyboardControl keyboard_control_values; keyboard_control_values.bell_percent = Int_val(ml_bell_percent); keyboard_control_values.bell_pitch = Int_val(ml_bell_pitch); keyboard_control_values.bell_duration = Int_val(ml_bell_duration); //GET_STATUS XChangeKeyboardControl( Display_val(dpy), KBBellPercent & KBBellPitch & KBBellDuration, &keyboard_control_values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } CAMLprim value ml_XChangeKeyboardControl_key_click_percent( value dpy, value ml_key_click_percent ) { XKeyboardControl keyboard_control_values; keyboard_control_values.key_click_percent = Int_val(ml_key_click_percent); //GET_STATUS XChangeKeyboardControl( Display_val(dpy), KBKeyClickPercent, &keyboard_control_values ); //CHECK_STATUS(XChangeKeyboardControl,1); return Val_unit; } /* TODO: place */ CAMLprim value ml_XChangePointerControl( value dpy, value do_accel, value do_threshold, value accel_numerator, value accel_denominator, value threshold ) { //GET_STATUS XChangePointerControl( Display_val(dpy), Bool_val(do_accel), Bool_val(do_threshold), Int_val(accel_numerator), Int_val(accel_denominator), Int_val(threshold) ); //CHECK_STATUS(XChangePointerControl,1); return Val_unit; } CAMLprim value ml_XChangePointerControl_bytecode( value * argv, int argn ) { return ml_XChangePointerControl( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5] ); } CAMLprim value ml_XGetPointerControl( value dpy ) { CAMLparam1(dpy); CAMLlocal1( pnt_ctrl ); int accel_numerator; int accel_denominator; int threshold; //GET_STATUS XGetPointerControl( Display_val(dpy), &accel_numerator, &accel_denominator, &threshold ); //CHECK_STATUS(XGetPointerControl, TODO ); pnt_ctrl = caml_alloc(3, 0); Store_field( pnt_ctrl, 0, Val_int(accel_numerator) ); Store_field( pnt_ctrl, 1, Val_int(accel_denominator) ); Store_field( pnt_ctrl, 2, Val_int(threshold) ); CAMLreturn( pnt_ctrl ); } /* ScreenSaver */ CAMLprim value ml_XForceScreenSaver( value dpy, value mode ) { GET_STATUS XForceScreenSaver( Display_val(dpy), ( Long_val(mode) ? ScreenSaverReset : ScreenSaverActive ) ); CHECK_STATUS(XForceScreenSaver,1); return Val_unit; } static const int prefer_blanking_table[] = { DontPreferBlanking, PreferBlanking, DefaultBlanking }; #define Prefer_blanking_val(i) (prefer_blanking_table[Long_val(i)]) static inline value Val_prefer_blanking(int v) { switch (v) { case DontPreferBlanking: return Val_int(0); case PreferBlanking: return Val_int(1); case DefaultBlanking: return Val_int(2); } return Val_int(0); } static const int allow_exposures_table[] = { DontAllowExposures, AllowExposures, DefaultExposures }; #define Allow_exposures_val(i) (allow_exposures_table[Long_val(i)]) static inline value Val_allow_exposures(int v) { switch (v) { case DontAllowExposures: return Val_int(0); case AllowExposures: return Val_int(1); case DefaultExposures: return Val_int(2); } return Val_int(0); } CAMLprim value ml_XGetScreenSaver( value dpy ) { CAMLparam1( dpy ); CAMLlocal1( tpl ); int timeout; int interval; int prefer_blanking; int allow_exposures; GET_STATUS XGetScreenSaver( Display_val(dpy), &timeout, &interval, &prefer_blanking, &allow_exposures ); CHECK_STATUS(XGetScreenSaver,1); tpl = caml_alloc(4, 0); Store_field( tpl, 0, Val_int(timeout) ); Store_field( tpl, 1, Val_int(interval) ); Store_field( tpl, 2, Val_prefer_blanking(prefer_blanking) ); Store_field( tpl, 3, Val_allow_exposures(allow_exposures) ); CAMLreturn( tpl ); } CAMLprim value ml_XSetScreenSaver( value dpy, value timeout, value interval, value prefer_blanking, value allow_exposures ) { //GET_STATUS XSetScreenSaver( Display_val(dpy), Int_val(timeout), Int_val(interval), Prefer_blanking_val(prefer_blanking), Allow_exposures_val(allow_exposures) ); //CHECK_STATUS(XSetScreenSaver,1); return Val_unit; } CAMLprim value ml_XActivateScreenSaver( value dpy ) { //GET_STATUS XActivateScreenSaver( Display_val(dpy) ); //CHECK_STATUS(XActivateScreenSaver,1); return Val_unit; } CAMLprim value ml_XResetScreenSaver( value dpy ) { //GET_STATUS XResetScreenSaver( Display_val(dpy) ); //CHECK_STATUS(XResetScreenSaver,1); return Val_unit; } /* {{{ (Screen *) */ CAMLprim value ml_XDefaultScreenOfDisplay( value dpy ) { Screen *scr = _xDefaultScreenOfDisplay( Display_val(dpy) ); return Val_XScreen(scr); } CAMLprim value ml_XScreenOfDisplay( value dpy, value screen_number ) { Screen *scr = _xScreenOfDisplay( Display_val(dpy), ScreenNB_val(screen_number) ); return Val_XScreen(scr); } CAMLprim value ml_XDefaultVisualOfScreen( value xscreen ) { Visual *visual = _xDefaultVisualOfScreen( XScreen_val(xscreen) ); return Val_Visual(visual); } CAMLprim value ml_XRootWindowOfScreen( value xscreen ) { return Val_Window( _xRootWindowOfScreen( XScreen_val(xscreen) )); } CAMLprim value ml_XBlackPixelOfScreen( value xscreen ) { unsigned long px = _xBlackPixelOfScreen( XScreen_val(xscreen) ); return Val_pixel_color(px); } CAMLprim value ml_XWhitePixelOfScreen( value xscreen ) { unsigned long px = _xWhitePixelOfScreen( XScreen_val(xscreen) ); return Val_pixel_color(px); } CAMLprim value ml_XDefaultColormapOfScreen( value xscreen ) { Colormap cmap = _xDefaultColormapOfScreen( XScreen_val(xscreen) ); return Val_Colormap(cmap); } CAMLprim value ml_XDefaultDepthOfScreen( value xscreen ) { return Val_int( _xDefaultDepthOfScreen( XScreen_val(xscreen) )); } CAMLprim value ml_XDefaultGCOfScreen( value xscreen ) { GC gc = _xDefaultGCOfScreen( XScreen_val(xscreen) ); Display *dpy = _xDisplayOfScreen( XScreen_val(xscreen) ); return Val_GC(gc, Val_Display(dpy)); } CAMLprim value ml_XDisplayOfScreen( value xscreen ) { Display *dpy = _xDisplayOfScreen( XScreen_val(xscreen) ); return Val_Display(dpy); } CAMLprim value ml_XWidthOfScreen( value xscreen ) { return Val_int( _xWidthOfScreen( XScreen_val(xscreen) )); } CAMLprim value ml_XHeightOfScreen( value xscreen ) { return Val_int( _xHeightOfScreen( XScreen_val(xscreen) )); } CAMLprim value ml_XScreenNumberOfScreen( value xscreen ) { return Val_screenNB( XScreenNumberOfScreen( XScreen_val(xscreen) )); } /* }}} */ /* {{{ ICCCM routines */ #if 0 Status XReconfigureWMWindow( Display* /* display */, Window /* w */, int /* screen_number */, unsigned int /* mask */, XWindowChanges* /* changes */ ); Status XGetWMProtocols( Display* /* display */, Window /* w */, Atom** /* protocols_return */, int* /* count_return */ ); Status XSetWMProtocols( Display* /* display */, Window /* w */, Atom* /* protocols */, int /* count */ ); #endif CAMLprim value ml_XIconifyWindow( value dpy, value win, value screen_number ) { GET_STATUS XIconifyWindow( Display_val(dpy), Window_val(win), ScreenNB_val(screen_number) ); CHECK_STATUS(XIconifyWindow,1); return Val_unit; } CAMLprim value ml_XWithdrawWindow( value dpy, value win, value screen_number ) { GET_STATUS XWithdrawWindow( Display_val(dpy), Window_val(win), ScreenNB_val(screen_number) ); CHECK_STATUS(XWithdrawWindow,1); return Val_unit; } CAMLprim value ml_XGetCommand( value dpy, value win ) { CAMLparam2(dpy, win); CAMLlocal1(cmds); char** argv; int argc = 0; Status st = XGetCommand( Display_val(dpy), Window_val(win), &argv, &argc ); if (!st) { cmds = caml_alloc(0, 0); // return an empty array instead of an exception } else { int i; cmds = caml_alloc(argc, 0); for (i=0; i<argc; ++i) { Store_field(cmds, i, caml_copy_string(argv[i])); } XFreeStringList(argv); } CAMLreturn(cmds); } #if 0 Status XGetWMColormapWindows( Display* /* display */, Window /* w */, Window** /* windows_return */, int* /* count_return */ ); Status XSetWMColormapWindows( Display* /* display */, Window /* w */, Window* /* colormap_windows */, int /* count */ ); void XFreeStringList( char** /* list */ ); int XSetTransientForHint( Display* /* display */, Window /* w */, Window /* prop_window */ ); #endif /* }}} */ /* {{{ Cursor */ /* XC_arrow, XC_top_left_arrow, XC_hand1, XC_pirate, XC_question_arrow, XC_exchange, XC_spraycan, XC_watch, XC_xterm, XC_crosshair, XC_sb_v_double_arrow, XC_sb_h_double_arrow, XC_top_side, XC_bottom_side, XC_left_side, XC_right_side, XC_top_left_corner, XC_top_right_corner, XC_bottom_right_corner, XC_bottom_left_corner, */ #include <X11/cursorfont.h> static const unsigned int cursor_shape_table[] = { XC_X_cursor, XC_arrow, XC_based_arrow_down, XC_based_arrow_up, XC_boat, XC_bogosity, XC_bottom_left_corner, XC_bottom_right_corner, XC_bottom_side, XC_bottom_tee, XC_box_spiral, XC_center_ptr, XC_circle, XC_clock, XC_coffee_mug, XC_cross, XC_cross_reverse, XC_crosshair, XC_diamond_cross, XC_dot, XC_dotbox, XC_double_arrow, XC_draft_large, XC_draft_small, XC_draped_box, XC_exchange, XC_fleur, XC_gobbler, XC_gumby, XC_hand1, XC_hand2, XC_heart, XC_icon, XC_iron_cross, XC_left_ptr, XC_left_side, XC_left_tee, XC_leftbutton, XC_ll_angle, XC_lr_angle, XC_man, XC_middlebutton, XC_mouse, XC_pencil, XC_pirate, XC_plus, XC_question_arrow, XC_right_ptr, XC_right_side, XC_right_tee, XC_rightbutton, XC_rtl_logo, XC_sailboat, XC_sb_down_arrow, XC_sb_h_double_arrow, XC_sb_left_arrow, XC_sb_right_arrow, XC_sb_up_arrow, XC_sb_v_double_arrow, XC_shuttle, XC_sizing, XC_spider, XC_spraycan, XC_star, XC_target, XC_tcross, XC_top_left_arrow, XC_top_left_corner, XC_top_right_corner, XC_top_side, XC_top_tee, XC_trek, XC_ul_angle, XC_umbrella, XC_ur_angle, XC_watch, XC_xterm, }; CAMLprim value ml_XCreateFontCursor( value dpy, value shape ) { Cursor cur = XCreateFontCursor( Display_val(dpy), cursor_shape_table[ Long_val(shape) ] ); return Val_Cursor(cur); } CAMLprim value ml_XDefineCursor( value dpy, value win, value cur ) { //GET_STATUS XDefineCursor( Display_val(dpy), Window_val(win), Cursor_val(cur) ); //CHECK_STATUS(XDefineCursor,1); return Val_unit; } CAMLprim value ml_XRecolorCursor( value dpy, value cur, value foreground, value background ) { //GET_STATUS XRecolorCursor( Display_val(dpy), Cursor_val(cur), XColor_val(foreground), XColor_val(background) ); //CHECK_STATUS(XRecolorCursor,1); return Val_unit; } /* }}} */ /* {{{ Font */ #define XFontStruct_val(v) ((XFontStruct *)(v)) #define Val_XFontStruct(fs) ((value)(fs)) CAMLprim value ml_XSetFont( value dpy, value gc, value font ) { //GET_STATUS XSetFont( Display_val(dpy), GC_val(gc), Font_val(font) ); //CHECK_STATUS(XSetFont,1); return Val_unit; } CAMLprim value ml_XLoadQueryFont( value dpy, value name ) { XFontStruct *fs = XLoadQueryFont( Display_val(dpy), String_val(name) ); return Val_XFontStruct(fs); } CAMLprim value ml_XQueryFont( value dpy, value font ) { XFontStruct *fs = XQueryFont( Display_val(dpy), Font_val(font) ); return Val_XFontStruct(fs); } CAMLprim value ml_XQueryFontGC( value dpy, value gc ) { XFontStruct *fs = XQueryFont( Display_val(dpy), XGContextFromGC(GC_val(gc)) ); return Val_XFontStruct(fs); } #if 0 XFontStruct { XExtData *ext_data; /* hook for extension to hang data */ Font fid; /* Font id for this font */ unsigned direction; /* hint about direction the font is painted */ unsigned min_char_or_byte2;/* first character */ unsigned max_char_or_byte2;/* last character */ unsigned min_byte1; /* first row that exists */ unsigned max_byte1; /* last row that exists */ Bool all_chars_exist;/* flag if all characters have non-zero size*/ unsigned default_char; /* char to print for undefined character */ int n_properties; /* how many properties there are */ XFontProp *properties; /* pointer to array of additional properties*/ XCharStruct min_bounds; /* minimum bounds over all existing char*/ XCharStruct max_bounds; /* maximum bounds over all existing char*/ XCharStruct *per_char; /* first_char to last_char information */ int ascent; /* log. extent above baseline for spacing */ int descent; /* log. descent below baseline for spacing */ } #endif #define FNTST_GET(field_c_type, field_name, Val_conv, ml_type) \ \ CAMLprim value \ ml_XFontStruct_get_##field_name( value vfs ) \ { \ return Val_conv((XFontStruct_val(vfs))->field_name); \ } #define FNTST_GML(field_c_type, field_name, Val_conv, ml_type) \ external xFontStruct_##field_name: xFontStruct -> ml_type = quote(ml_XFontStruct_get_##field_name) FNTST_GET(Font, fid, Val_Font, font) FNTST_GET(int, ascent, Val_int, int) FNTST_GET(int, descent, Val_int, int) FNTST_GET(Bool, all_chars_exist, Val_bool, bool) CAMLprim value ml_XFontStruct_get_height( value vfs ) { CAMLparam1( vfs ); CAMLlocal1( height ); XFontStruct * fs = XFontStruct_val(vfs); height = caml_alloc(2, 0); Store_field( height, 0, Val_int(fs->ascent) ); Store_field( height, 1, Val_int(fs->descent) ); CAMLreturn( height ); } CAMLprim value ml_XFontStruct_get_height2( value dpy, value gc ) { CAMLparam2( dpy, gc ); CAMLlocal1( height ); XFontStruct *fs = XQueryFont( Display_val(dpy), XGContextFromGC(GC_val(gc)) ); if (!fs) caml_failwith("XFontStruct"); height = caml_alloc(2, 0); Store_field( height, 0, Val_int(fs->ascent) ); Store_field( height, 1, Val_int(fs->descent) ); CAMLreturn( height ); } CAMLprim value ml_XTextWidth( value vfs, value str ) { XFontStruct * fs = XFontStruct_val(vfs); //if (fs == NULL) // caml_invalid_argument("xTextWidth"); return Val_int( XTextWidth( fs, String_val(str), caml_string_length(str) )); } CAMLprim value ml_xFontStruct_max_bounds( value vfs ) { CAMLparam1( vfs ); CAMLlocal1( cst ); XFontStruct * fs = XFontStruct_val(vfs); XCharStruct * b = &(fs->max_bounds); cst = caml_alloc(5, 0); Store_field( cst, 0, Val_int(b->lbearing) ); Store_field( cst, 1, Val_int(b->rbearing) ); Store_field( cst, 2, Val_int(b->width) ); Store_field( cst, 3, Val_int(b->ascent) ); Store_field( cst, 4, Val_int(b->descent) ); CAMLreturn( cst ); } CAMLprim value ml_xFontStruct_min_bounds( value vfs ) { CAMLparam1( vfs ); CAMLlocal1( cst ); XFontStruct * fs = XFontStruct_val(vfs); XCharStruct * b = &(fs->min_bounds); cst = caml_alloc(5, 0); Store_field( cst, 0, Val_int(b->lbearing) ); Store_field( cst, 1, Val_int(b->rbearing) ); Store_field( cst, 2, Val_int(b->width) ); Store_field( cst, 3, Val_int(b->ascent) ); Store_field( cst, 4, Val_int(b->descent) ); CAMLreturn( cst ); } /* int XTextWidth16( XFontStruct* font_struct, _Xconst XChar2b* string, int count ); */ /* }}} */ // vim: sw=4 sts=4 ts=4 et fdm=marker
fccm/ocaml-xlib
src/wrap_glx_p2t.c
/* OCaml bindings for the GLX library (as part of OCaml-Xlib). Copyright (C) 2008, 2009 by <NAME> printf("monnier.florent@%s", "gmail.<EMAIL>"); OCaml-Xlib is FLOSS software: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software. */ #define GL_GLEXT_PROTOTYPES #define GLX_GLXEXT_PROTOTYPES #include <GL/gl.h> #include <GL/glx.h> #define CAML_NAME_SPACE 1 #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/custom.h> #include <caml/fail.h> #include "wrap_xlib.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wrap_glx.h" static PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT_func = NULL; static PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT_func = NULL; static int glx_p2t_not_available = 0; #define no_glx_p2t() \ do{ caml_failwith("GLX_P2T: unable to load functions for the " \ "extension GLX_EXT_texture_from_pixmap"); }while(0) CAMLprim value ml_init_glx_p2t( value unit ) { glXBindTexImageEXT_func = (PFNGLXBINDTEXIMAGEEXTPROC) glXGetProcAddress((GLubyte *) "glXBindTexImageEXT"); glXReleaseTexImageEXT_func = (PFNGLXRELEASETEXIMAGEEXTPROC) glXGetProcAddress((GLubyte*) "glXReleaseTexImageEXT"); if (!glXBindTexImageEXT_func || !glXReleaseTexImageEXT_func) { glx_p2t_not_available = 1; } else { glx_p2t_not_available = 0; } /* * Don't raise a failure here in case the functions of this * extenstion are not used. For example if the user code first * checks if this extension is available or not before calling * these functions (but the functions are there, so this current * init_glx_p2t() would have been called when the module was open. */ return Val_unit; } static const int tex_image_buffer_table[] = { GLX_FRONT_LEFT_EXT, GLX_FRONT_RIGHT_EXT, GLX_BACK_LEFT_EXT, GLX_BACK_RIGHT_EXT, GLX_FRONT_EXT, GLX_BACK_EXT, GLX_AUX0_EXT, GLX_AUX1_EXT, GLX_AUX2_EXT, GLX_AUX3_EXT, GLX_AUX4_EXT, GLX_AUX5_EXT, GLX_AUX6_EXT, GLX_AUX7_EXT, GLX_AUX8_EXT, GLX_AUX9_EXT, }; CAMLprim value ml_glXBindTexImageEXT( value dpy, value drawable, value buffer, value ml_attrib_list ) { if (glx_p2t_not_available) no_glx_p2t(); glXBindTexImageEXT_func( Display_val(dpy), GLXDrawable_val(drawable), tex_image_buffer_table[Long_val(buffer)], NULL // const int *attrib_list /* TODO */ ); return Val_unit; } CAMLprim value ml_glXReleaseTexImageEXT( value dpy, value drawable, value buffer ) { if (glx_p2t_not_available) no_glx_p2t(); glXReleaseTexImageEXT_func( Display_val(dpy), GLXDrawable_val(drawable), tex_image_buffer_table[Long_val(buffer)] ); return Val_unit; } CAMLprim value ml_glXCreatePixmapEXT( value dpy, value config, value pixmap, value attrib_list ) { static const int GLX_TEXTURE_FORMAT_EXT_table[] = { GLX_TEXTURE_FORMAT_NONE_EXT, GLX_TEXTURE_FORMAT_RGB_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT, }; static const int GLX_TEXTURE_TARGET_EXT_table[] = { GLX_TEXTURE_1D_EXT, GLX_TEXTURE_2D_EXT, GLX_TEXTURE_RECTANGLE_EXT, }; int attrs[30]; // TODO: is this thread safe ? or should we do a malloc ? int i = 0; while ( attrib_list != Val_emptylist ) { value attrib = Field(attrib_list, 0); { switch (Tag_val(attrib)) { case 0: attrs[i] = GLX_TEXTURE_FORMAT_EXT; attrs[i+1] = GLX_TEXTURE_FORMAT_EXT_table[Long_val(Field(attrib,0))]; break; case 1: attrs[i] = GLX_TEXTURE_TARGET_EXT; attrs[i+1] = GLX_TEXTURE_TARGET_EXT_table[Long_val(Field(attrib,0))]; break; case 2: attrs[i] = GLX_MIPMAP_TEXTURE_EXT; attrs[i+1] = Bool_val(Field(attrib,0)); break; default: caml_failwith("glXCreatePixmap: variant handling bug"); } i += 2; } attrib_list = Field(attrib_list,1); if (i >= 28) break; } attrs[i] = None; GLXPixmap glXPixmap = glXCreatePixmap( Display_val(dpy), GLXFBConfig_val(config), Pixmap_val(pixmap), attrs ); return Val_GLXPixmap(glXPixmap); } // vim: sw=4 sts=4 ts=4 et fdm=marker
tmihalik/cphalcon
ext/mvc/model/metadata/apc.c
<reponame>tmihalik/cphalcon<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/object.h" #include "kernel/concat.h" #include "kernel/fcall.h" /** * Phalcon\Mvc\Model\MetaData\Apc * * Stores model meta-data in the APC cache. Data will erased if the web server is restarted * * By default meta-data is stored for 48 hours (172800 seconds) * * You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-app-id') * *<code> * $metaData = new Phalcon\Mvc\Model\Metadata\Apc(array( * 'prefix' => 'my-app-id', * 'lifetime' => 86400 * )); *</code> */ /** * Phalcon\Mvc\Model\MetaData\Apc initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_MetaData_Apc){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\Model\\MetaData, Apc, mvc_model_metadata_apc, "phalcon\\mvc\\model\\metadata", phalcon_mvc_model_metadata_apc_method_entry, 0); zend_declare_property_string(phalcon_mvc_model_metadata_apc_ce, SL("_prefix"), "", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_model_metadata_apc_ce, SL("_ttl"), 172800, ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_model_metadata_apc_ce TSRMLS_CC, 1, phalcon_mvc_model_metadatainterface_ce); return SUCCESS; } /** * Phalcon\Mvc\Model\MetaData\Apc constructor * * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Apc, __construct){ zval *options = NULL, *prefix, *ttl, *empty_array; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } if (Z_TYPE_P(options) == IS_ARRAY) { if (phalcon_array_isset_string(options, SS("prefix"))) { PHALCON_OBS_VAR(prefix); phalcon_array_fetch_string(&prefix, options, SL("prefix"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_prefix"), prefix TSRMLS_CC); } if (phalcon_array_isset_string(options, SS("lifetime"))) { PHALCON_OBS_VAR(ttl); phalcon_array_fetch_string(&ttl, options, SL("lifetime"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_ttl"), ttl TSRMLS_CC); } } PHALCON_INIT_VAR(empty_array); array_init(empty_array); phalcon_update_property_zval(this_ptr, SL("_metaData"), empty_array TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Reads meta-data from APC * * @param string $key * @return array */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Apc, read){ zval *key, *prefix, *apc_key, *data; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &key) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(prefix); phalcon_read_property(&prefix, this_ptr, SL("_prefix"), PH_NOISY_CC); PHALCON_INIT_VAR(apc_key); PHALCON_CONCAT_SVV(apc_key, "$PMM$", prefix, key); PHALCON_INIT_VAR(data); PHALCON_CALL_FUNC_PARAMS_1(data, "apc_fetch", apc_key); if (Z_TYPE_P(data) == IS_ARRAY) { RETURN_CCTOR(data); } RETURN_MM_NULL(); } /** * Writes the meta-data to APC * * @param string $key * @param array $data */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Apc, write){ zval *key, *data, *prefix, *apc_key, *ttl; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &key, &data) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(prefix); phalcon_read_property(&prefix, this_ptr, SL("_prefix"), PH_NOISY_CC); PHALCON_INIT_VAR(apc_key); PHALCON_CONCAT_SVV(apc_key, "$PMM$", prefix, key); PHALCON_OBS_VAR(ttl); phalcon_read_property(&ttl, this_ptr, SL("_ttl"), PH_NOISY_CC); PHALCON_CALL_FUNC_PARAMS_3_NORETURN("apc_store", apc_key, data, ttl); PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/http/responseinterface.h
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_http_responseinterface_ce; PHALCON_INIT_CLASS(Phalcon_Http_ResponseInterface); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setstatuscode, 0, 0, 2) ZEND_ARG_INFO(0, code) ZEND_ARG_INFO(0, message) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setheader, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setrawheader, 0, 0, 1) ZEND_ARG_INFO(0, header) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setexpires, 0, 0, 1) ZEND_ARG_INFO(0, datetime) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setcontenttype, 0, 0, 1) ZEND_ARG_INFO(0, contentType) ZEND_ARG_INFO(0, charset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_redirect, 0, 0, 0) ZEND_ARG_INFO(0, location) ZEND_ARG_INFO(0, externalRedirect) ZEND_ARG_INFO(0, statusCode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_setcontent, 0, 0, 1) ZEND_ARG_INFO(0, content) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_responseinterface_appendcontent, 0, 0, 1) ZEND_ARG_INFO(0, content) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_http_responseinterface_method_entry){ PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setStatusCode, arginfo_phalcon_http_responseinterface_setstatuscode) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, getHeaders, NULL) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setHeader, arginfo_phalcon_http_responseinterface_setheader) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setRawHeader, arginfo_phalcon_http_responseinterface_setrawheader) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, resetHeaders, NULL) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setExpires, arginfo_phalcon_http_responseinterface_setexpires) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setNotModified, NULL) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setContentType, arginfo_phalcon_http_responseinterface_setcontenttype) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, redirect, arginfo_phalcon_http_responseinterface_redirect) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, setContent, arginfo_phalcon_http_responseinterface_setcontent) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, appendContent, arginfo_phalcon_http_responseinterface_appendcontent) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, getContent, NULL) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, sendHeaders, NULL) PHP_ABSTRACT_ME(Phalcon_Http_ResponseInterface, send, NULL) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/view/engine/volt.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/operators.h" #include "kernel/require.h" #include "kernel/string.h" #include "kernel/array.h" /** * Phalcon\Mvc\View\Engine\Volt * * Designer friendly and fast template engine for PHP written in C */ /** * Phalcon\Mvc\View\Engine\Volt initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine_Volt){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\View\\Engine, Volt, mvc_view_engine_volt, "phalcon\\mvc\\view\\engine", phalcon_mvc_view_engine_volt_method_entry, 0); zend_declare_property_null(phalcon_mvc_view_engine_volt_ce, SL("_options"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_ce, SL("_compiler"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_view_engine_volt_ce TSRMLS_CC, 1, phalcon_mvc_view_engineinterface_ce); return SUCCESS; } /** * Set Volt's options * * @param array $options */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, setOptions){ zval *options; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &options) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(options) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Options parameter must be an array"); return; } phalcon_update_property_zval(this_ptr, SL("_options"), options TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Return Volt's options * * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, getOptions){ RETURN_MEMBER(this_ptr, "_options"); } /** * Returns the Volt's compiler * * @return Phalcon\Mvc\View\Engine\Volt\Compiler */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, getCompiler){ zval *compiler = NULL, *view, *options, *dependency_injector; PHALCON_MM_GROW(); PHALCON_OBS_VAR(compiler); phalcon_read_property(&compiler, this_ptr, SL("_compiler"), PH_NOISY_CC); if (Z_TYPE_P(compiler) != IS_OBJECT) { PHALCON_OBS_VAR(view); phalcon_read_property(&view, this_ptr, SL("_view"), PH_NOISY_CC); PHALCON_OBS_VAR(options); phalcon_read_property(&options, this_ptr, SL("_options"), PH_NOISY_CC); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); PHALCON_INIT_NVAR(compiler); object_init_ex(compiler, phalcon_mvc_view_engine_volt_compiler_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(compiler, "__construct", view); /** * Pass the IoC to the compiler only it's an object */ if (Z_TYPE_P(dependency_injector) == IS_OBJECT) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(compiler, "setdi", dependency_injector); } /** * Pass the options to the compiler only they're an array */ if (Z_TYPE_P(options) == IS_ARRAY) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(compiler, "setoptions", options); } phalcon_update_property_zval(this_ptr, SL("_compiler"), compiler TSRMLS_CC); } RETURN_CCTOR(compiler); } /** * Renders a view using the template engine * * @param string $templatePath * @param array $params * @param boolean $mustClean */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, render){ zval *template_path, *params, *must_clean = NULL, *compiler; zval *compiled_template_path, *value = NULL, *key = NULL, *contents; zval *view; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &template_path, &params, &must_clean) == FAILURE) { RETURN_MM_NULL(); } if (!must_clean) { PHALCON_INIT_VAR(must_clean); ZVAL_BOOL(must_clean, 0); } if (PHALCON_IS_TRUE(must_clean)) { PHALCON_CALL_FUNC_NORETURN("ob_clean"); } /** * The compilation process is done by Phalcon\Mvc\View\Engine\Volt\Compiler */ PHALCON_INIT_VAR(compiler); PHALCON_CALL_METHOD(compiler, this_ptr, "getcompiler"); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(compiler, "compile", template_path); PHALCON_INIT_VAR(compiled_template_path); PHALCON_CALL_METHOD(compiled_template_path, compiler, "getcompiledtemplatepath"); /** * Export the variables the current symbol table */ if (Z_TYPE_P(params) == IS_ARRAY) { if (!phalcon_is_iterable(params, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (phalcon_set_symbol(key, value TSRMLS_CC) == FAILURE){ return; } zend_hash_move_forward_ex(ah0, &hp0); } } if (phalcon_require(compiled_template_path TSRMLS_CC) == FAILURE) { return; } if (PHALCON_IS_TRUE(must_clean)) { PHALCON_INIT_VAR(contents); PHALCON_CALL_FUNC(contents, "ob_get_contents"); PHALCON_OBS_VAR(view); phalcon_read_property(&view, this_ptr, SL("_view"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(view, "setcontent", contents); } PHALCON_MM_RESTORE(); } /** * Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen * * @param mixed $item * @return int */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, length){ zval *item, *length = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &item) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(length); ZVAL_LONG(length, 0); if (Z_TYPE_P(item) == IS_OBJECT) { phalcon_fast_count(length, item TSRMLS_CC); } else { if (Z_TYPE_P(item) == IS_ARRAY) { phalcon_fast_count(length, item TSRMLS_CC); } else { if (phalcon_function_exists_ex(SS("mb_strlen") TSRMLS_CC) == SUCCESS) { PHALCON_CALL_FUNC_PARAMS_1(length, "mb_strlen", item); } else { PHALCON_INIT_NVAR(length); phalcon_fast_strlen(length, item); } } } RETURN_CCTOR(length); } /** * Performs a string conversion * * @param string $text * @param string $from * @param string $to * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, converEncoding){ zval *text, *from, *to, *converted = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &text, &from, &to) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_function_exists_ex(SS("mb_convert_encoding") TSRMLS_CC) == SUCCESS) { PHALCON_INIT_VAR(converted); PHALCON_CALL_FUNC_PARAMS_3(converted, "mb_convert_encoding", text, from, to); RETURN_CCTOR(converted); } if (phalcon_function_exists_ex(SS("iconv") TSRMLS_CC) == SUCCESS) { PHALCON_INIT_NVAR(converted); PHALCON_CALL_FUNC_PARAMS_3(converted, "iconv", from, to, text); RETURN_CCTOR(converted); } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Any of 'mbstring' or 'iconv' is required to perform the charset conversion"); return; } /** * Extracts a slice from an string/array/traversable object value * * @param mixed $value */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, slice){ zval *value, *start, *end = NULL, *slice = NULL, *length = NULL, *position; zval *is_greater = NULL, *is_less = NULL, *current = NULL, *one, *range; zval *r0 = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &value, &start, &end) == FAILURE) { RETURN_MM_NULL(); } if (!end) { PHALCON_INIT_VAR(end); } /** * Objects must implement a Traversable interface */ if (Z_TYPE_P(value) == IS_OBJECT) { PHALCON_INIT_VAR(slice); array_init(slice); if (Z_TYPE_P(end) == IS_NULL) { PHALCON_INIT_VAR(length); phalcon_fast_count(length, value TSRMLS_CC); } else { PHALCON_CPY_WRT(length, end); } PHALCON_INIT_VAR(position); ZVAL_LONG(position, 0); PHALCON_CALL_METHOD_NORETURN(value, "rewind"); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, value, "valid"); if (zend_is_true(r0)) { } else { break; } PHALCON_INIT_NVAR(is_greater); is_smaller_or_equal_function(is_greater, start, position TSRMLS_CC); if (PHALCON_IS_TRUE(is_greater)) { PHALCON_INIT_NVAR(is_less); is_smaller_or_equal_function(is_less, position, length TSRMLS_CC); if (PHALCON_IS_TRUE(is_less)) { PHALCON_INIT_NVAR(current); PHALCON_CALL_METHOD(current, value, "current"); phalcon_array_append(&slice, current, PH_SEPARATE TSRMLS_CC); } } PHALCON_CALL_METHOD_NORETURN(value, "next"); PHALCON_SEPARATE(position); increment_function(position); } RETURN_CTOR(slice); } /** * Calculate the slice length */ if (Z_TYPE_P(end) != IS_NULL) { PHALCON_INIT_VAR(one); ZVAL_LONG(one, 1); PHALCON_INIT_VAR(range); sub_function(range, end, start TSRMLS_CC); PHALCON_INIT_NVAR(length); phalcon_add_function(length, range, one TSRMLS_CC); } else { PHALCON_INIT_NVAR(length); } /** * Use array_slice on arrays */ if (Z_TYPE_P(value) == IS_ARRAY) { PHALCON_INIT_NVAR(slice); PHALCON_CALL_FUNC_PARAMS_3(slice, "array_slice", value, start, length); RETURN_CTOR(slice); } /** * Use mb_substr if available */ if (phalcon_function_exists_ex(SS("mb_substr") TSRMLS_CC) == SUCCESS) { if (Z_TYPE_P(length) != IS_NULL) { PHALCON_INIT_NVAR(slice); PHALCON_CALL_FUNC_PARAMS_3(slice, "mb_substr", value, start, length); } else { PHALCON_INIT_NVAR(slice); PHALCON_CALL_FUNC_PARAMS_2(slice, "mb_substr", value, start); } RETURN_CCTOR(slice); } /** * Use the standard substr function */ if (Z_TYPE_P(length) != IS_NULL) { PHALCON_INIT_NVAR(slice); PHALCON_CALL_FUNC_PARAMS_3(slice, "substr", value, start, length); } else { PHALCON_INIT_NVAR(slice); PHALCON_CALL_FUNC_PARAMS_2(slice, "substr", value, start); } RETURN_CCTOR(slice); }
tmihalik/cphalcon
ext/kernel/require.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "php_main.h" #include "kernel/main.h" #include "kernel/require.h" #include "kernel/memory.h" #include "kernel/debug.h" #include "Zend/zend_exceptions.h" int PHALCON_FASTCALL phalcon_internal_require(zval *return_value, zval *require_path TSRMLS_DC){ int ret; char *file_path; unsigned int file_path_length; zend_file_handle file_handle; zval *result = NULL; int status = SUCCESS; int dummy = 0; zval **original_return_value = EG(return_value_ptr_ptr); zend_op **original_opline_ptr = EG(opline_ptr); zend_op_array *original_active_op_array = EG(active_op_array); zend_op_array *new_op_array = NULL; if (Z_TYPE_P(require_path) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Invalid require path value"); status = FAILURE; } else { file_path = Z_STRVAL_P(require_path); file_path_length = Z_STRLEN_P(require_path); ret = php_stream_open_for_zend_ex(file_path, &file_handle, ENFORCE_SAFE_MODE|USE_PATH|STREAM_OPEN_FOR_INCLUDE TSRMLS_CC); if (ret == SUCCESS) { if (!file_handle.opened_path) { file_handle.opened_path = estrndup(file_path, file_path_length); } EG(exit_status) = 0; PG(during_request_startup) = 0; if (file_handle.filename) { if ((file_handle.filename[0] != '-' || file_handle.filename[1] != 0) && file_handle.opened_path == NULL && file_handle.type != ZEND_HANDLE_FILENAME) { char realfile[MAXPATHLEN]; int realfile_len; dummy = 1; if(expand_filepath(file_handle.filename, realfile TSRMLS_CC)){ realfile_len = strlen(realfile); zend_hash_add(&EG(included_files), realfile, realfile_len+1, (void *)&dummy, sizeof(int), NULL); file_handle.opened_path = estrndup(realfile, realfile_len); } } } if (!dummy) { if (file_handle.opened_path) { zend_hash_add(&EG(included_files), file_handle.opened_path, file_path_length + 1, (void *)&dummy, sizeof(int), NULL); } } new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE TSRMLS_CC); zend_destroy_file_handle(&file_handle TSRMLS_CC); if (new_op_array) { EG(return_value_ptr_ptr) = &result; EG(active_op_array) = new_op_array; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } /** This provides compatibility with AOP extension */ new_op_array->type = ZEND_EVAL_CODE; zend_execute(new_op_array TSRMLS_CC); zend_exception_restore(TSRMLS_C); destroy_op_array(new_op_array TSRMLS_CC); efree(new_op_array); if (!EG(exception)) { if (EG(return_value_ptr_ptr)) { if (return_value) { COPY_PZVAL_TO_ZVAL(*return_value, result); } else { zval_ptr_dtor(EG(return_value_ptr_ptr)); } } } } EG(return_value_ptr_ptr) = original_return_value; EG(opline_ptr) = original_opline_ptr; EG(active_op_array) = original_active_op_array; if (EG(exception) || EG(exit_status) == 255) { status = FAILURE; } } else { zend_destroy_file_handle(&file_handle TSRMLS_CC); status = FAILURE; } } if (status == FAILURE){ phalcon_memory_restore_stack(TSRMLS_C); } return status; } /** * Do an internal require to a plain php file without taking care of the value returned by the file */ int PHALCON_FASTCALL phalcon_require(zval *require_path TSRMLS_DC){ return phalcon_internal_require(NULL, require_path TSRMLS_CC); } /** * Do an internal require to a plain php file taking care of the value returned by the file */ int PHALCON_FASTCALL phalcon_require_ret(zval *return_value, zval *require_path TSRMLS_DC){ return phalcon_internal_require(return_value, require_path TSRMLS_CC); }
tmihalik/cphalcon
ext/logger/adapter/file.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/string.h" #include "kernel/exception.h" #include "kernel/fcall.h" #include "kernel/concat.h" #include "kernel/object.h" /** * Phalcon\Logger\Adapter\File * * Adapter to store logs in plain text files * *<code> * $logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log"); * $logger->log("This is a message"); * $logger->log("This is an error", \Phalcon\Logger::ERROR); * $logger->error("This is another error"); * $logger->close(); *</code> */ /** * Phalcon\Logger\Adapter\File initializer */ PHALCON_INIT_CLASS(Phalcon_Logger_Adapter_File){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Logger\\Adapter, File, logger_adapter_file, "phalcon\\logger\\adapter", phalcon_logger_adapter_file_method_entry, 0); zend_declare_property_null(phalcon_logger_adapter_file_ce, SL("_fileHandler"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_logger_adapter_file_ce, SL("_path"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_logger_adapter_file_ce, SL("_options"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_logger_adapter_file_ce TSRMLS_CC, 1, phalcon_logger_adapterinterface_ce); return SUCCESS; } /** * Phalcon\Logger\Adapter\File constructor * * @param string $name * @param array $options */ PHP_METHOD(Phalcon_Logger_Adapter_File, __construct){ zval *name, *options = NULL, *mode = NULL, *handler, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &name, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } if (phalcon_array_isset_string(options, SS("mode"))) { PHALCON_OBS_VAR(mode); phalcon_array_fetch_string(&mode, options, SL("mode"), PH_NOISY_CC); if (phalcon_memnstr_str(mode, SL("r") TSRMLS_CC)) { PHALCON_THROW_EXCEPTION_STR(phalcon_logger_exception_ce, "Logger must be opened in append or write mode"); return; } } else { PHALCON_INIT_NVAR(mode); ZVAL_STRING(mode, "ab", 1); } /** * We use 'fopen' to respect to open-basedir directive */ PHALCON_INIT_VAR(handler); PHALCON_CALL_FUNC_PARAMS_2(handler, "fopen", name, mode); if (!zend_is_true(handler)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Can't open log file at '", name, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_logger_exception_ce, exception_message); return; } phalcon_update_property_zval(this_ptr, SL("_path"), name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_options"), options TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_fileHandler"), handler TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the internal formatter * * @return Phalcon\Logger\Formatter\Line */ PHP_METHOD(Phalcon_Logger_Adapter_File, getFormatter){ zval *formatter = NULL; PHALCON_MM_GROW(); PHALCON_OBS_VAR(formatter); phalcon_read_property(&formatter, this_ptr, SL("_formatter"), PH_NOISY_CC); if (Z_TYPE_P(formatter) != IS_OBJECT) { PHALCON_INIT_NVAR(formatter); object_init_ex(formatter, phalcon_logger_formatter_line_ce); PHALCON_CALL_METHOD_NORETURN(formatter, "__construct"); phalcon_update_property_zval(this_ptr, SL("_formatter"), formatter TSRMLS_CC); } RETURN_CCTOR(formatter); } /** * Writes the log to the file itself * * @param string $message * @param int $type * @param int $time */ PHP_METHOD(Phalcon_Logger_Adapter_File, logInternal){ zval *message, *type, *time, *file_handler, *formatter; zval *applied_format; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &message, &type, &time) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(file_handler); phalcon_read_property(&file_handler, this_ptr, SL("_fileHandler"), PH_NOISY_CC); if (!zend_is_true(file_handler)) { PHALCON_THROW_EXCEPTION_STR(phalcon_logger_exception_ce, "Cannot send message to the log because it is invalid"); return; } PHALCON_INIT_VAR(formatter); PHALCON_CALL_METHOD(formatter, this_ptr, "getformatter"); PHALCON_INIT_VAR(applied_format); PHALCON_CALL_METHOD_PARAMS_3(applied_format, formatter, "format", message, type, time); PHALCON_CALL_FUNC_PARAMS_2_NORETURN("fwrite", file_handler, applied_format); PHALCON_MM_RESTORE(); } /** * Closes the logger * * @return boolean */ PHP_METHOD(Phalcon_Logger_Adapter_File, close){ zval *file_handler, *success; PHALCON_MM_GROW(); PHALCON_OBS_VAR(file_handler); phalcon_read_property(&file_handler, this_ptr, SL("_fileHandler"), PH_NOISY_CC); PHALCON_INIT_VAR(success); PHALCON_CALL_FUNC_PARAMS_1(success, "fclose", file_handler); RETURN_CCTOR(success); } /** * Opens the internal file handler after unserialization * */ PHP_METHOD(Phalcon_Logger_Adapter_File, __wakeup){ zval *path, *options, *mode = NULL, *file_handler; PHALCON_MM_GROW(); PHALCON_OBS_VAR(path); phalcon_read_property(&path, this_ptr, SL("_path"), PH_NOISY_CC); PHALCON_OBS_VAR(options); phalcon_read_property(&options, this_ptr, SL("_options"), PH_NOISY_CC); if (phalcon_array_isset_string(options, SS("mode"))) { PHALCON_OBS_VAR(mode); phalcon_array_fetch_string(&mode, options, SL("mode"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(mode); ZVAL_STRING(mode, "ab", 1); } /** * Re-open the file handler if the logger was serialized */ PHALCON_INIT_VAR(file_handler); PHALCON_CALL_FUNC_PARAMS_2(file_handler, "fopen", path, mode); phalcon_update_property_zval(this_ptr, SL("_fileHandler"), file_handler TSRMLS_CC); PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/mvc/model/managerinterface.h
<reponame>tmihalik/cphalcon<filename>ext/mvc/model/managerinterface.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_model_managerinterface_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_Model_ManagerInterface); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_initialize, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_isinitialized, 0, 0, 1) ZEND_ARG_INFO(0, modelName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_load, 0, 0, 1) ZEND_ARG_INFO(0, modelName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_addhasone, 0, 0, 4) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, referenceModel) ZEND_ARG_INFO(0, referencedFields) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_addbelongsto, 0, 0, 4) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, referenceModel) ZEND_ARG_INFO(0, referencedFields) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_addhasmany, 0, 0, 4) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, referenceModel) ZEND_ARG_INFO(0, referencedFields) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_existsbelongsto, 0, 0, 2) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_existshasmany, 0, 0, 2) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_existshasone, 0, 0, 2) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_getbelongstorecords, 0, 0, 4) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_ARG_INFO(0, record) ZEND_ARG_INFO(0, parameters) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_gethasmanyrecords, 0, 0, 4) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_ARG_INFO(0, record) ZEND_ARG_INFO(0, parameters) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_gethasonerecords, 0, 0, 4) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, modelName) ZEND_ARG_INFO(0, modelRelation) ZEND_ARG_INFO(0, record) ZEND_ARG_INFO(0, parameters) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_getbelongsto, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_gethasmany, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_gethasone, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_gethasoneandhasmany, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_getrelations, 0, 0, 1) ZEND_ARG_INFO(0, modelName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_getrelationsbetween, 0, 0, 2) ZEND_ARG_INFO(0, firstModel) ZEND_ARG_INFO(0, secondModel) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_createquery, 0, 0, 1) ZEND_ARG_INFO(0, phql) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_executequery, 0, 0, 1) ZEND_ARG_INFO(0, phql) ZEND_ARG_INFO(0, placeholders) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_createbuilder, 0, 0, 0) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_addbehavior, 0, 0, 2) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, behavior) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_notifyevent, 0, 0, 2) ZEND_ARG_INFO(0, eventName) ZEND_ARG_INFO(0, model) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_managerinterface_missingmethod, 0, 0, 3) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, eventName) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_model_managerinterface_method_entry){ PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, initialize, arginfo_phalcon_mvc_model_managerinterface_initialize) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, isInitialized, arginfo_phalcon_mvc_model_managerinterface_isinitialized) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getLastInitialized, NULL) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, load, arginfo_phalcon_mvc_model_managerinterface_load) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, addHasOne, arginfo_phalcon_mvc_model_managerinterface_addhasone) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, addBelongsTo, arginfo_phalcon_mvc_model_managerinterface_addbelongsto) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, addHasMany, arginfo_phalcon_mvc_model_managerinterface_addhasmany) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, existsBelongsTo, arginfo_phalcon_mvc_model_managerinterface_existsbelongsto) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, existsHasMany, arginfo_phalcon_mvc_model_managerinterface_existshasmany) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, existsHasOne, arginfo_phalcon_mvc_model_managerinterface_existshasone) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getBelongsToRecords, arginfo_phalcon_mvc_model_managerinterface_getbelongstorecords) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getHasManyRecords, arginfo_phalcon_mvc_model_managerinterface_gethasmanyrecords) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getHasOneRecords, arginfo_phalcon_mvc_model_managerinterface_gethasonerecords) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getBelongsTo, arginfo_phalcon_mvc_model_managerinterface_getbelongsto) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getHasMany, arginfo_phalcon_mvc_model_managerinterface_gethasmany) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getHasOne, arginfo_phalcon_mvc_model_managerinterface_gethasone) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getHasOneAndHasMany, arginfo_phalcon_mvc_model_managerinterface_gethasoneandhasmany) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getRelations, arginfo_phalcon_mvc_model_managerinterface_getrelations) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getRelationsBetween, arginfo_phalcon_mvc_model_managerinterface_getrelationsbetween) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, createQuery, arginfo_phalcon_mvc_model_managerinterface_createquery) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, executeQuery, arginfo_phalcon_mvc_model_managerinterface_executequery) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, createBuilder, arginfo_phalcon_mvc_model_managerinterface_createbuilder) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, addBehavior, arginfo_phalcon_mvc_model_managerinterface_addbehavior) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, notifyEvent, arginfo_phalcon_mvc_model_managerinterface_notifyevent) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, missingMethod, arginfo_phalcon_mvc_model_managerinterface_missingmethod) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_ManagerInterface, getLastQuery, NULL) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/view/engine/volt.h
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_view_engine_volt_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine_Volt); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, setOptions); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, getOptions); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, getCompiler); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, render); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, length); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, converEncoding); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt, slice); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_setoptions, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_render, 0, 0, 2) ZEND_ARG_INFO(0, templatePath) ZEND_ARG_INFO(0, params) ZEND_ARG_INFO(0, mustClean) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_length, 0, 0, 1) ZEND_ARG_INFO(0, item) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_converencoding, 0, 0, 3) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, from) ZEND_ARG_INFO(0, to) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_slice, 0, 0, 2) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, end) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_view_engine_volt_method_entry){ PHP_ME(Phalcon_Mvc_View_Engine_Volt, setOptions, arginfo_phalcon_mvc_view_engine_volt_setoptions, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, getOptions, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, getCompiler, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, render, arginfo_phalcon_mvc_view_engine_volt_render, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, length, arginfo_phalcon_mvc_view_engine_volt_length, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, converEncoding, arginfo_phalcon_mvc_view_engine_volt_converencoding, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt, slice, arginfo_phalcon_mvc_view_engine_volt_slice, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/view/engine/volt/compiler.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/exception.h" #include "kernel/array.h" #include "kernel/operators.h" #include "kernel/fcall.h" #include "kernel/concat.h" #include "kernel/string.h" #include "kernel/file.h" #include "mvc/view/engine/volt/scanner.h" #include "mvc/view/engine/volt/volt.h" /** * Phalcon\Mvc\View\Engine\Volt\Compiler * * This class reads and compiles Volt templates into PHP plain code * *<code> * $compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler(); * $compiler->compile('views/partials/header.volt'); * require $compiler->getCompiledTemplatePath(); *</code> */ /** * Phalcon\Mvc\View\Engine\Volt\Compiler initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine_Volt_Compiler){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc\\View\\Engine\\Volt, Compiler, mvc_view_engine_volt_compiler, phalcon_mvc_view_engine_volt_compiler_method_entry, 0); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_view"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_options"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_arrayHelpers"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_view_engine_volt_compiler_ce, SL("_level"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_view_engine_volt_compiler_ce, SL("_exprLevel"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_mvc_view_engine_volt_compiler_ce, SL("_extended"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_mvc_view_engine_volt_compiler_ce, SL("_autoescape"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_extendedBlocks"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_currentBlock"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_blocks"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_functions"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_filters"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_currentPath"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_view_engine_volt_compiler_ce, SL("_compiledTemplatePath"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_view_engine_volt_compiler_ce TSRMLS_CC, 1, phalcon_di_injectionawareinterface_ce); return SUCCESS; } /** * Phalcon\Mvc\View\Engine\Volt\Compiler * * @param Phalcon\Mvc\ViewInterface $view */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, __construct){ zval *view = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &view) == FAILURE) { RETURN_MM_NULL(); } if (!view) { PHALCON_INIT_VAR(view); } if (Z_TYPE_P(view) == IS_OBJECT) { phalcon_update_property_zval(this_ptr, SL("_view"), view TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Sets the compiler options * * @param array $options */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, setOptions){ zval *options; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &options) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_options"), options TSRMLS_CC); } /** * Returns the compiler options * * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getOptions){ RETURN_MEMBER(this_ptr, "_options"); } /** * Sets the dependency injector * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, setDI){ zval *dependency_injector; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Dependency Injector is invalid"); return; } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the internal dependency injector * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Register a new function in the compiler * * @param string $name * @param Closure|string $definition * @return Phalcon\Mvc\View\Engine\Volt\Compiler */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, addFunction){ zval *name, *definition; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &name, &definition) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(name) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "The function name must be an string"); return; } phalcon_update_property_array(this_ptr, SL("_functions"), name, definition TSRMLS_CC); RETURN_THIS(); } /** * Register the user registered functions * * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getFunctions){ RETURN_MEMBER(this_ptr, "_functions"); } /** * Register a new filter in the compiler * * @param string $name * @param Closure|string $definition * @return Phalcon\Mvc\View\Engine\Volt\Compiler */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, addFilter){ zval *name, *definition; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &name, &definition) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(name) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "The function name must be a string"); return; } phalcon_update_property_array(this_ptr, SL("_filters"), name, definition TSRMLS_CC); RETURN_THIS(); } /** * Register the user registered filters * * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getFilters){ RETURN_MEMBER(this_ptr, "_filters"); } /** * Resolves attribute reading * * @param array $expr * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, attributeReader){ zval *expr, *expr_code, *left, *left_type, *variable; zval *dependency_injector, *is_service, *left_code; zval *right, *right_type, *member, *right_code; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &expr) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(expr) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted function call"); return; } PHALCON_INIT_VAR(expr_code); PHALCON_OBS_VAR(left); phalcon_array_fetch_string(&left, expr, SL("left"), PH_NOISY_CC); PHALCON_OBS_VAR(left_type); phalcon_array_fetch_string(&left_type, left, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(left_type, 265)) { PHALCON_OBS_VAR(variable); phalcon_array_fetch_string(&variable, left, SL("value"), PH_NOISY_CC); /** * Services registered in the dependency injector container are availables always */ PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) == IS_OBJECT) { PHALCON_INIT_VAR(is_service); PHALCON_CALL_METHOD_PARAMS_1(is_service, dependency_injector, "has", variable); if (zend_is_true(is_service)) { PHALCON_SCONCAT_SV(expr_code, "$this->", variable); } else { PHALCON_SCONCAT_SV(expr_code, "$", variable); } } else { PHALCON_SCONCAT_SV(expr_code, "$", variable); } } else { PHALCON_INIT_VAR(left_code); PHALCON_CALL_METHOD_PARAMS_1(left_code, this_ptr, "expression", left); if (!PHALCON_IS_LONG(left_type, 46)) { if (!PHALCON_IS_LONG(left_type, 350)) { PHALCON_SCONCAT_SVS(expr_code, "(", left_code, ")"); } else { phalcon_concat_self(&expr_code, left_code TSRMLS_CC); } } else { phalcon_concat_self(&expr_code, left_code TSRMLS_CC); } } phalcon_concat_self_str(&expr_code, SL("->") TSRMLS_CC); PHALCON_OBS_VAR(right); phalcon_array_fetch_string(&right, expr, SL("right"), PH_NOISY_CC); PHALCON_OBS_VAR(right_type); phalcon_array_fetch_string(&right_type, right, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(right_type, 265)) { PHALCON_OBS_VAR(member); phalcon_array_fetch_string(&member, right, SL("value"), PH_NOISY_CC); phalcon_concat_self(&expr_code, member TSRMLS_CC); } else { PHALCON_INIT_VAR(right_code); PHALCON_CALL_METHOD_PARAMS_1(right_code, this_ptr, "expression", right); phalcon_concat_self(&expr_code, right_code TSRMLS_CC); } RETURN_CCTOR(expr_code); } /** * Resolves function intermediate code into PHP function calls * * @param array $expr * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, functionCall){ zval *expr, *code = NULL, *func_arguments = NULL, *arguments = NULL; zval *name_expr, *name_type, *name = NULL, *functions; zval *definition, *parameters, *line = NULL, *file = NULL, *exception_message = NULL; zval *extended_blocks, *current_block, *expr_level; zval *block, *escaped_code = NULL, *str_code = NULL, *camelized; zval *method, *class_name, *array_helpers = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &expr) == FAILURE) { RETURN_MM_NULL(); } /** * Valid filters are always arrays */ if (Z_TYPE_P(expr) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted function call"); return; } PHALCON_INIT_VAR(code); PHALCON_INIT_VAR(func_arguments); if (phalcon_array_isset_string(expr, SS("arguments"))) { PHALCON_OBS_NVAR(func_arguments); phalcon_array_fetch_string(&func_arguments, expr, SL("arguments"), PH_NOISY_CC); PHALCON_INIT_VAR(arguments); PHALCON_CALL_METHOD_PARAMS_1(arguments, this_ptr, "expression", func_arguments); } else { PHALCON_INIT_NVAR(arguments); ZVAL_STRING(arguments, "", 1); } PHALCON_OBS_VAR(name_expr); phalcon_array_fetch_string(&name_expr, expr, SL("name"), PH_NOISY_CC); PHALCON_OBS_VAR(name_type); phalcon_array_fetch_string(&name_type, name_expr, SL("type"), PH_NOISY_CC); /** * Check if it's a single function */ if (PHALCON_IS_LONG(name_type, 265)) { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, name_expr, SL("value"), PH_NOISY_CC); /** * Check if it's a user defined function */ PHALCON_OBS_VAR(functions); phalcon_read_property(&functions, this_ptr, SL("_functions"), PH_NOISY_CC); if (Z_TYPE_P(functions) == IS_ARRAY) { if (phalcon_array_isset(functions, name)) { PHALCON_OBS_VAR(definition); phalcon_array_fetch(&definition, functions, name, PH_NOISY_CC); if (Z_TYPE_P(definition) == IS_STRING) { RETURN_CCTOR(definition); } if (Z_TYPE_P(definition) == IS_OBJECT) { if (phalcon_is_instance_of(definition, SL("Closure") TSRMLS_CC)) { PHALCON_INIT_VAR(parameters); array_init_size(parameters, 2); phalcon_array_append(&parameters, arguments, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&parameters, func_arguments, PH_SEPARATE TSRMLS_CC); PHALCON_CALL_FUNC_PARAMS_2(code, "call_user_func_array", definition, parameters); RETURN_CCTOR(code); } } PHALCON_OBS_VAR(line); phalcon_array_fetch_string(&line, expr, SL("line"), PH_NOISY_CC); PHALCON_OBS_VAR(file); phalcon_array_fetch_string(&file, expr, SL("file"), PH_NOISY_CC); PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Invalid definition for user function '", name, "' in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } } /** * This function includes the previous rendering stage */ if (PHALCON_IS_STRING(name, "get_content")) { PHALCON_INIT_NVAR(code); ZVAL_STRING(code, "$this->getContent()", 1); RETURN_CCTOR(code); } /** * Alias of 'get_content' */ if (PHALCON_IS_STRING(name, "content")) { PHALCON_INIT_NVAR(code); ZVAL_STRING(code, "$this->getContent()", 1); RETURN_CCTOR(code); } /** * This function includes views of volt or others template engines dynamically */ if (PHALCON_IS_STRING(name, "partial")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->partial(", arguments, ")"); RETURN_CCTOR(code); } /** * This function embeds the parent block in the current block */ if (PHALCON_IS_STRING(name, "super")) { PHALCON_OBS_VAR(extended_blocks); phalcon_read_property(&extended_blocks, this_ptr, SL("_extendedBlocks"), PH_NOISY_CC); if (Z_TYPE_P(extended_blocks) == IS_ARRAY) { PHALCON_OBS_VAR(current_block); phalcon_read_property(&current_block, this_ptr, SL("_currentBlock"), PH_NOISY_CC); if (phalcon_array_isset(extended_blocks, current_block)) { PHALCON_OBS_VAR(expr_level); phalcon_read_property(&expr_level, this_ptr, SL("_exprLevel"), PH_NOISY_CC); PHALCON_OBS_VAR(block); phalcon_array_fetch(&block, extended_blocks, current_block, PH_NOISY_CC); if (Z_TYPE_P(block) == IS_ARRAY) { PHALCON_INIT_NVAR(code); PHALCON_CALL_METHOD_PARAMS_1(code, this_ptr, "_statementlistorextends", block); if (PHALCON_IS_LONG(expr_level, 1)) { PHALCON_CPY_WRT(escaped_code, code); } else { PHALCON_INIT_VAR(escaped_code); PHALCON_CALL_FUNC_PARAMS_1(escaped_code, "addslashes", code); } } else { if (PHALCON_IS_LONG(expr_level, 1)) { PHALCON_CPY_WRT(escaped_code, block); } else { PHALCON_INIT_NVAR(escaped_code); PHALCON_CALL_FUNC_PARAMS_1(escaped_code, "addslashes", block); } } /** * If the super() is the first level we don't escape it */ if (PHALCON_IS_LONG(expr_level, 1)) { PHALCON_CPY_WRT(str_code, escaped_code); } else { PHALCON_INIT_VAR(str_code); PHALCON_CONCAT_SVS(str_code, "'", escaped_code, "'"); } RETURN_CCTOR(str_code); } } PHALCON_MM_RESTORE(); RETURN_STRING("''", 1); } PHALCON_INIT_VAR(camelized); phalcon_camelize(camelized, name TSRMLS_CC); PHALCON_INIT_VAR(method); PHALCON_CALL_FUNC_PARAMS_1(method, "lcfirst", camelized); PHALCON_INIT_VAR(class_name); ZVAL_STRING(class_name, "Phalcon\\Tag", 1); /** * Check if it's a method in Phalcon\Tag */ if (phalcon_method_exists(class_name, method TSRMLS_CC) == SUCCESS) { PHALCON_OBS_VAR(array_helpers); phalcon_read_property(&array_helpers, this_ptr, SL("_arrayHelpers"), PH_NOISY_CC); if (Z_TYPE_P(array_helpers) != IS_ARRAY) { PHALCON_INIT_NVAR(array_helpers); array_init_size(array_helpers, 13); add_assoc_bool_ex(array_helpers, SS("link_to"), 1); add_assoc_bool_ex(array_helpers, SS("image"), 1); add_assoc_bool_ex(array_helpers, SS("form"), 1); add_assoc_bool_ex(array_helpers, SS("select"), 1); add_assoc_bool_ex(array_helpers, SS("select_static"), 1); add_assoc_bool_ex(array_helpers, SS("submit_button"), 1); add_assoc_bool_ex(array_helpers, SS("radio_field"), 1); add_assoc_bool_ex(array_helpers, SS("checkbox_field"), 1); add_assoc_bool_ex(array_helpers, SS("file_field"), 1); add_assoc_bool_ex(array_helpers, SS("hidden_field"), 1); add_assoc_bool_ex(array_helpers, SS("password_field"), 1); add_assoc_bool_ex(array_helpers, SS("text_area"), 1); add_assoc_bool_ex(array_helpers, SS("text_field"), 1); phalcon_update_property_zval(this_ptr, SL("_arrayHelpers"), array_helpers TSRMLS_CC); } if (phalcon_array_isset(array_helpers, name)) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVS(code, "Phalcon\\Tag::", method, "(array(", arguments, "))"); } else { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVS(code, "Phalcon\\Tag::", method, "(", arguments, ")"); } RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "url")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->url->get(", arguments, ")"); RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "date")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "date(", arguments, ")"); RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "time")) { PHALCON_INIT_NVAR(code); ZVAL_STRING(code, "time()", 1); RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "dump")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "var_dump(", arguments, ")"); RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "version")) { PHALCON_INIT_NVAR(code); ZVAL_STRING(code, "Phalcon\\Version::get()", 1); RETURN_CCTOR(code); } if (PHALCON_IS_STRING(name, "version_id")) { PHALCON_INIT_NVAR(code); ZVAL_STRING(code, "Phalcon\\Version::getId()", 1); RETURN_CCTOR(code); } /** * Read PHP constants in templates */ if (PHALCON_IS_STRING(name, "constant")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "constant(", arguments, ")"); RETURN_CCTOR(code); } /** * The function doesn't exist throw an exception */ PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, expr, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, expr, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Undefined function '", name, "' in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } else { PHALCON_INIT_NVAR(name); PHALCON_CALL_METHOD_PARAMS_1(name, this_ptr, "expression", name_expr); PHALCON_INIT_NVAR(code); PHALCON_CONCAT_VSVS(code, name, "(", arguments, ")"); RETURN_CCTOR(code); } PHALCON_MM_RESTORE(); } /** * Resolves filter intermediate code into a valid PHP expression * * @param array $test * @param string $left * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveTest){ zval *test, *left, *type, *name = NULL, *code = NULL, *test_name, *test_arguments = NULL; zval *arguments = NULL, *right_code; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &test, &left) == FAILURE) { RETURN_MM_NULL(); } /** * Valid tests are always arrays */ if (Z_TYPE_P(test) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted test"); return; } PHALCON_OBS_VAR(type); phalcon_array_fetch_string(&type, test, SL("type"), PH_NOISY_CC); /** * Check if right part is a single identifier */ if (PHALCON_IS_LONG(type, 265)) { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, test, SL("value"), PH_NOISY_CC); /** * Empty uses the PHP's empty operator */ if (PHALCON_IS_STRING(name, "empty")) { PHALCON_INIT_VAR(code); PHALCON_CONCAT_SVS(code, "empty(", left, ")"); RETURN_CTOR(code); } /** * Check if a value is even */ if (PHALCON_IS_STRING(name, "even")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "(((", left, ") % 2) == 0)"); RETURN_CTOR(code); } /** * Check if a value is odd */ if (PHALCON_IS_STRING(name, "odd")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "(((", left, ") % 2) != 0)"); RETURN_CTOR(code); } /** * Check if a value is numeric */ if (PHALCON_IS_STRING(name, "numeric")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "is_numeric(", left, ")"); RETURN_CTOR(code); } /** * Check if a value is scalar */ if (PHALCON_IS_STRING(name, "scalar")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "is_scalar(", left, ")"); RETURN_CTOR(code); } /** * Check if a value is iterable */ if (PHALCON_IS_STRING(name, "iterable")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVS(code, "(is_array(", left, ") || (", left, ") instanceof Traversable)"); RETURN_CTOR(code); } } /** * Check if right part is a function call */ if (PHALCON_IS_LONG(type, 350)) { PHALCON_OBS_VAR(test_name); phalcon_array_fetch_string(&test_name, test, SL("name"), PH_NOISY_CC); if (phalcon_array_isset_string(test_name, SS("value"))) { /** * Checks if a value is divisible by other */ PHALCON_OBS_NVAR(name); phalcon_array_fetch_string(&name, test_name, SL("value"), PH_NOISY_CC); if (PHALCON_IS_STRING(name, "divisibleby")) { PHALCON_OBS_VAR(test_arguments); phalcon_array_fetch_string(&test_arguments, test, SL("arguments"), PH_NOISY_CC); PHALCON_INIT_VAR(arguments); PHALCON_CALL_METHOD_PARAMS_1(arguments, this_ptr, "expression", test_arguments); PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVS(code, "(((", left, ") % (", arguments, ")) == 0)"); RETURN_CTOR(code); } /** * Checks if a value is equals to other */ if (PHALCON_IS_STRING(name, "sameas")) { PHALCON_OBS_NVAR(test_arguments); phalcon_array_fetch_string(&test_arguments, test, SL("arguments"), PH_NOISY_CC); PHALCON_INIT_NVAR(arguments); PHALCON_CALL_METHOD_PARAMS_1(arguments, this_ptr, "expression", test_arguments); PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVS(code, "(", left, ") === (", arguments, ")"); RETURN_CTOR(code); } } } /** * Fall back to the equals operator */ PHALCON_INIT_VAR(right_code); PHALCON_CALL_METHOD_PARAMS_1(right_code, this_ptr, "expression", test); PHALCON_INIT_NVAR(code); PHALCON_CONCAT_VSV(code, left, " == ", right_code); RETURN_CTOR(code); } /** * Resolves filter intermediate code into PHP function calls * * @param array $filter * @param string $left * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveFilter){ zval *filter, *left, *code = NULL, *type, *name = NULL, *function_name; zval *line = NULL, *file = NULL, *exception_message = NULL, *func_arguments = NULL; zval *arguments = NULL, *resolved_expr, *resolved_param; zval *filters, *definition, *parameters; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &filter, &left) == FAILURE) { RETURN_MM_NULL(); } /** * Valid filters are always arrays */ if (Z_TYPE_P(filter) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted filter"); return; } PHALCON_INIT_VAR(code); PHALCON_OBS_VAR(type); phalcon_array_fetch_string(&type, filter, SL("type"), PH_NOISY_CC); /** * Check if the filter is a single identifier */ if (PHALCON_IS_LONG(type, 265)) { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, filter, SL("value"), PH_NOISY_CC); } else { if (PHALCON_IS_LONG(type, 350)) { PHALCON_OBS_VAR(function_name); phalcon_array_fetch_string(&function_name, filter, SL("name"), PH_NOISY_CC); PHALCON_OBS_NVAR(name); phalcon_array_fetch_string(&name, function_name, SL("value"), PH_NOISY_CC); } else { /** * Unknown filter throw an exception */ PHALCON_OBS_VAR(line); phalcon_array_fetch_string(&line, filter, SL("line"), PH_NOISY_CC); PHALCON_OBS_VAR(file); phalcon_array_fetch_string(&file, filter, SL("file"), PH_NOISY_CC); PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVSV(exception_message, "Unknown filter type in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } } PHALCON_INIT_VAR(func_arguments); PHALCON_INIT_VAR(arguments); /** * Resolve arguments */ if (phalcon_array_isset_string(filter, SS("arguments"))) { PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, filter, SL("file"), PH_NOISY_CC); PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, filter, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(func_arguments); phalcon_array_fetch_string(&func_arguments, filter, SL("arguments"), PH_NOISY_CC); /** * 'default' filter is not the first argument, improve this! */ if (!PHALCON_IS_STRING(name, "default")) { PHALCON_INIT_VAR(resolved_expr); array_init_size(resolved_expr, 4); add_assoc_long_ex(resolved_expr, SS("type"), 364); phalcon_array_update_string(&resolved_expr, SL("value"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&resolved_expr, SL("file"), &file, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&resolved_expr, SL("line"), &line, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(resolved_param); array_init_size(resolved_param, 3); phalcon_array_update_string(&resolved_param, SL("expr"), &resolved_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&resolved_param, SL("file"), &file, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&resolved_param, SL("line"), &line, PH_COPY | PH_SEPARATE TSRMLS_CC); Z_SET_ISREF_P(func_arguments); PHALCON_CALL_FUNC_PARAMS_2_NORETURN("array_unshift", func_arguments, resolved_param); Z_UNSET_ISREF_P(func_arguments); } PHALCON_CALL_METHOD_PARAMS_1(arguments, this_ptr, "expression", func_arguments); } else { PHALCON_CPY_WRT(arguments, left); } /** * Check if it's a user defined filter */ PHALCON_OBS_VAR(filters); phalcon_read_property(&filters, this_ptr, SL("_filters"), PH_NOISY_CC); if (Z_TYPE_P(filters) == IS_ARRAY) { if (phalcon_array_isset(filters, name)) { PHALCON_OBS_VAR(definition); phalcon_array_fetch(&definition, filters, name, PH_NOISY_CC); /** * The definition is a string */ if (Z_TYPE_P(definition) == IS_STRING) { PHALCON_CONCAT_VSVS(code, definition, "(", arguments, ")"); RETURN_CCTOR(code); } /** * The definition is a closure */ if (Z_TYPE_P(definition) == IS_OBJECT) { if (phalcon_is_instance_of(definition, SL("Closure") TSRMLS_CC)) { PHALCON_INIT_VAR(parameters); array_init_size(parameters, 2); phalcon_array_append(&parameters, arguments, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&parameters, func_arguments, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(code); PHALCON_CALL_FUNC_PARAMS_2(code, "call_user_func_array", definition, parameters); RETURN_CCTOR(code); } } /** * Invalid filter definition throw an exception */ PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, filter, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, filter, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Invalid definition for user filter '", name, "' in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } } /** * 'length' uses the length method implemented in the Volt adapter */ if (PHALCON_IS_STRING(name, "length")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->length(", arguments, ")"); RETURN_CCTOR(code); } /** * 'e' filter uses the escaper component */ if (PHALCON_IS_STRING(name, "e")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->escaper->escapeHtml(", arguments, ")"); RETURN_CCTOR(code); } /** * 'escape' filter uses the escaper component */ if (PHALCON_IS_STRING(name, "escape")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->escaper->escapeHtml(", arguments, ")"); RETURN_CCTOR(code); } /** * 'escapecss' filter uses the escaper component to filter css */ if (PHALCON_IS_STRING(name, "escape_css")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->escaper->escapeCss(", arguments, ")"); RETURN_CCTOR(code); } /** * 'escapejs' filter uses the escaper component to escape javascript */ if (PHALCON_IS_STRING(name, "escape_js")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->escaper->escapeJs(", arguments, ")"); RETURN_CCTOR(code); } /** * 'escapeattr' filter uses the escaper component to escape html attributes */ if (PHALCON_IS_STRING(name, "escape_attr")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->escaper->escapeHtmlAttr(", arguments, ")"); RETURN_CCTOR(code); } /** * 'trim' calls the "trim" function in the PHP userland */ if (PHALCON_IS_STRING(name, "trim")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "trim(", arguments, ")"); RETURN_CCTOR(code); } /** * 'striptags' calls the "strip_tags" function in the PHP userland */ if (PHALCON_IS_STRING(name, "striptags")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "strip_tags(", arguments, ")"); RETURN_CCTOR(code); } /** * 'urlencode' calls the "urlencode" function in the PHP userland */ if (PHALCON_IS_STRING(name, "url_encode")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "urlencode(", arguments, ")"); RETURN_CCTOR(code); } /** * 'slashes' calls the "addslashes" function in the PHP userland */ if (PHALCON_IS_STRING(name, "slashes")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "addslashes(", arguments, ")"); RETURN_CCTOR(code); } /** * 'stripslashes' calls the "stripslashes" function in the PHP userland */ if (PHALCON_IS_STRING(name, "stripslashes")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "stripslashes(", arguments, ")"); RETURN_CCTOR(code); } /** * 'nl2br' calls the "nl2br" function in the PHP userland */ if (PHALCON_IS_STRING(name, "nl2br")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "nl2br(", arguments, ")"); RETURN_CCTOR(code); } /** * 'keys' uses calls the "array_keys" function in the PHP userland */ if (PHALCON_IS_STRING(name, "keys")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "array_keys(", arguments, ")"); RETURN_CCTOR(code); } /** * 'join' uses calls the "join" function in the PHP userland */ if (PHALCON_IS_STRING(name, "join")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "join(", arguments, ")"); RETURN_CCTOR(code); } /** * 'lowercase' calls the "strtolower" function or "mb_strtolower" if the mbstring * extension is loaded */ if (PHALCON_IS_STRING(name, "lowercase")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "Phalcon\\Text::lower(", arguments, ")"); RETURN_CCTOR(code); } /** * 'lowercase' calls the "strtolower" function or "mb_strtolower" if the mbstring * extension is loaded */ if (PHALCON_IS_STRING(name, "lower")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "Phalcon\\Text::lower(", arguments, ")"); RETURN_CCTOR(code); } /** * 'uppercase' calls the "strtouppwer" function or "mb_strtoupper" if the mbstring * extension is loaded */ if (PHALCON_IS_STRING(name, "uppercase")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "Phalcon\\Text::upper(", arguments, ")"); RETURN_CCTOR(code); } /** * 'uppercase' calls the "strtouppwer" function or "mb_strtoupper" if the mbstring * extension is loaded */ if (PHALCON_IS_STRING(name, "upper")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "Phalcon\\Text::upper(", arguments, ")"); RETURN_CCTOR(code); } /** * 'sort' calls the "asort" function in the PHP userland */ if (PHALCON_IS_STRING(name, "sort")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "asort(", arguments, ")"); RETURN_CCTOR(code); } /** * 'json_encode' calls the "json_encode" function in the PHP userland */ if (PHALCON_IS_STRING(name, "json_encode")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "json_encode(", arguments, ")"); RETURN_CCTOR(code); } /** * 'json_decode' calls the "json_decode" function in the PHP userland */ if (PHALCON_IS_STRING(name, "json_decode")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "json_decode(", arguments, ")"); RETURN_CCTOR(code); } /** * 'format' calls the "sprintf" function in the PHP userland */ if (PHALCON_IS_STRING(name, "format")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "sprintf(", arguments, ")"); RETURN_CCTOR(code); } /** * 'abs' calls the "abs" function in the PHP userland */ if (PHALCON_IS_STRING(name, "abs")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "abs(", arguments, ")"); RETURN_CCTOR(code); } /** * 'slice' slices string/arrays/traversable objects */ if (PHALCON_IS_STRING(name, "slice")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->slice(", arguments, ")"); RETURN_CCTOR(code); } /** * 'default' checks if a variable is empty */ if (PHALCON_IS_STRING(name, "default")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVSVSVS(code, "(empty(", left, ") ? (", arguments, ") : (", left, "))"); RETURN_CCTOR(code); } /** * This function uses mbstring or iconv to convert strings from one chartset to * another */ if (PHALCON_IS_STRING(name, "convert_encoding")) { PHALCON_INIT_NVAR(code); PHALCON_CONCAT_SVS(code, "$this->convertEncoding(", arguments, ")"); RETURN_CCTOR(code); } /** * Unknown filter throw an exception */ PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, filter, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, filter, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Unknown filter \"", name, "\" in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } /** * Resolves an expression node in an AST volt tree * * @param array $expr * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, expression){ zval *expr, *expr_code = NULL, *items = NULL, *single_expr = NULL, *single_expr_expr = NULL; zval *single_expr_code = NULL, *name = NULL, *parameter = NULL, *type = NULL; zval *left = NULL, *left_code = NULL, *right_code = NULL, *right = NULL, *value = NULL; zval *single_quote = NULL, *escaped_quoute = NULL, *escaped_string = NULL; zval *start = NULL, *start_code = NULL, *end = NULL, *end_code = NULL, *line = NULL, *file = NULL; zval *exception_message = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &expr) == FAILURE) { RETURN_MM_NULL(); } /** * Valid expressions are always arrays */ if (Z_TYPE_P(expr) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted expression"); return; } PHALCON_INIT_VAR(expr_code); phalcon_property_incr(this_ptr, SL("_exprLevel") TSRMLS_CC); while (1) { if (!phalcon_array_isset_string(expr, SS("type"))) { PHALCON_INIT_NVAR(items); array_init(items); if (!phalcon_is_iterable(expr, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(single_expr); PHALCON_OBS_NVAR(single_expr_expr); phalcon_array_fetch_string(&single_expr_expr, single_expr, SL("expr"), PH_NOISY_CC); PHALCON_INIT_NVAR(single_expr_code); PHALCON_CALL_METHOD_PARAMS_1(single_expr_code, this_ptr, "expression", single_expr_expr); if (phalcon_array_isset_string(single_expr, SS("name"))) { PHALCON_OBS_NVAR(name); phalcon_array_fetch_string(&name, single_expr, SL("name"), PH_NOISY_CC); PHALCON_INIT_NVAR(parameter); PHALCON_CONCAT_SVSV(parameter, "'", name, "' => ", single_expr_code); phalcon_array_append(&items, parameter, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&items, single_expr_code, PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_NVAR(expr_code); phalcon_fast_join_str(expr_code, SL(", "), items TSRMLS_CC); break; } PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, expr, SL("type"), PH_NOISY_CC); /** * Attribute reading needs special handling */ if (PHALCON_IS_LONG(type, 46)) { PHALCON_INIT_NVAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "attributereader", expr); break; } /** * Left part of expression is always resolved */ if (phalcon_array_isset_string(expr, SS("left"))) { PHALCON_OBS_NVAR(left); phalcon_array_fetch_string(&left, expr, SL("left"), PH_NOISY_CC); PHALCON_INIT_NVAR(left_code); PHALCON_CALL_METHOD_PARAMS_1(left_code, this_ptr, "expression", left); } /** * Operator 'is' also needs special handling */ if (PHALCON_IS_LONG(type, 311)) { PHALCON_OBS_NVAR(right_code); phalcon_array_fetch_string(&right_code, expr, SL("right"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_code); PHALCON_CALL_METHOD_PARAMS_2(expr_code, this_ptr, "resolvetest", right_code, left_code); break; } /** * We don't resolve the right expression for filters */ if (PHALCON_IS_LONG(type, 124)) { PHALCON_OBS_NVAR(right_code); phalcon_array_fetch_string(&right_code, expr, SL("right"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_code); PHALCON_CALL_METHOD_PARAMS_2(expr_code, this_ptr, "resolvefilter", right_code, left_code); break; } /** * From here, right part of expression is always resolved */ if (phalcon_array_isset_string(expr, SS("right"))) { PHALCON_OBS_NVAR(right); phalcon_array_fetch_string(&right, expr, SL("right"), PH_NOISY_CC); PHALCON_INIT_NVAR(right_code); PHALCON_CALL_METHOD_PARAMS_1(right_code, this_ptr, "expression", right); } PHALCON_INIT_NVAR(expr_code); switch (phalcon_get_intval(type)) { case 33: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SV(expr_code, "!", right_code); break; case 42: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " * ", right_code); break; case 43: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " + ", right_code); break; case 45: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " - ", right_code); break; case 47: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " / ", right_code); break; case 37: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " % ", right_code); break; case 60: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " < ", right_code); break; case 61: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " > ", right_code); break; case 62: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " > ", right_code); break; case 126: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " . ", right_code); break; case 360: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVS(expr_code, "array(", left_code, ")"); break; case 258: PHALCON_OBS_NVAR(expr_code); phalcon_array_fetch_string(&expr_code, expr, SL("value"), PH_NOISY_CC); break; case 259: PHALCON_OBS_NVAR(expr_code); phalcon_array_fetch_string(&expr_code, expr, SL("value"), PH_NOISY_CC); break; case 260: PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_NVAR(single_quote); ZVAL_STRING(single_quote, "'", 1); PHALCON_INIT_NVAR(escaped_quoute); ZVAL_STRING(escaped_quoute, "\\'", 1); PHALCON_INIT_NVAR(escaped_string); phalcon_fast_str_replace(escaped_string, single_quote, escaped_quoute, value TSRMLS_CC); PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVS(expr_code, "'", escaped_string, "'"); break; case 261: PHALCON_INIT_NVAR(expr_code); ZVAL_STRING(expr_code, "null", 1); break; case 262: PHALCON_INIT_NVAR(expr_code); ZVAL_STRING(expr_code, "false", 1); break; case 263: PHALCON_INIT_NVAR(expr_code); ZVAL_STRING(expr_code, "true", 1); break; case 265: PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SV(expr_code, "$", value); break; case 266: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " && ", right_code); break; case 267: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " || ", right_code); break; case 270: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " <= ", right_code); break; case 271: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " >= ", right_code); break; case 272: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " == ", right_code); break; case 273: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " != ", right_code); break; case 274: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " === ", right_code); break; case 275: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSV(expr_code, left_code, " !== ", right_code); break; case 276: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVSVS(expr_code, "range(", left_code, ", ", right_code, ")"); break; case 350: PHALCON_INIT_NVAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "functioncall", expr); break; case 356: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVS(expr_code, "(", left_code, ")"); break; case 361: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_VSVS(expr_code, left_code, "[", right_code, "]"); break; case 365: /** * Evaluate the start part of the slice */ if (phalcon_array_isset_string(expr, SS("start"))) { PHALCON_OBS_NVAR(start); phalcon_array_fetch_string(&start, expr, SL("start"), PH_NOISY_CC); PHALCON_INIT_NVAR(start_code); PHALCON_CALL_METHOD_PARAMS_1(start_code, this_ptr, "expression", start); } else { PHALCON_INIT_NVAR(start_code); ZVAL_STRING(start_code, "null", 1); } /** * Evaluate the end part of the slice */ if (phalcon_array_isset_string(expr, SS("end"))) { PHALCON_OBS_NVAR(end); phalcon_array_fetch_string(&end, expr, SL("end"), PH_NOISY_CC); PHALCON_INIT_NVAR(end_code); PHALCON_CALL_METHOD_PARAMS_1(end_code, this_ptr, "expression", end); } else { PHALCON_INIT_NVAR(end_code); ZVAL_STRING(end_code, "null", 1); } PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVSVSVS(expr_code, "$this->slice(", left_code, ", ", start_code, ", ", end_code, ")"); break; case 362: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVS(expr_code, "!isset(", left_code, ")"); break; case 363: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SVS(expr_code, "isset(", left_code, ")"); break; case 367: PHALCON_INIT_NVAR(expr_code); PHALCON_CONCAT_SV(expr_code, "-", right_code); break; case 364: PHALCON_OBS_NVAR(expr_code); phalcon_array_fetch_string(&expr_code, expr, SL("value"), PH_NOISY_CC); break; default: PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, expr, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, expr, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Unknown expression ", type, " in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } break; } phalcon_property_decr(this_ptr, SL("_exprLevel") TSRMLS_CC); RETURN_CCTOR(expr_code); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementListOrExtends){ zval *statements, *is_statement_list = NULL, *statement = NULL; zval *code; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statements) == FAILURE) { RETURN_MM_NULL(); } /** * Resolve the statement list as normal */ if (Z_TYPE_P(statements) != IS_ARRAY) { RETURN_CCTOR(statements); } /** * If all elements in the statement list are arrays we resolve this as a * statementList */ PHALCON_INIT_VAR(is_statement_list); ZVAL_BOOL(is_statement_list, 1); if (!phalcon_array_isset_string(statements, SS("type"))) { if (!phalcon_is_iterable(statements, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(statement); if (Z_TYPE_P(statement) != IS_ARRAY) { PHALCON_INIT_NVAR(is_statement_list); ZVAL_BOOL(is_statement_list, 0); break; } zend_hash_move_forward_ex(ah0, &hp0); } } /** * Resolve the statement list as normal */ if (PHALCON_IS_TRUE(is_statement_list)) { PHALCON_INIT_VAR(code); PHALCON_CALL_METHOD_PARAMS_1(code, this_ptr, "_statementlist", statements); RETURN_CCTOR(code); } /** * Is an array but not an statement list? */ RETURN_CCTOR(statements); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileForeach){ zval *statement, *extends_mode = NULL, *compilation; zval *expr, *expr_code, *variable, *key, *if_expr; zval *if_expr_code, *block_statements, *code; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &statement, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } PHALCON_INIT_VAR(compilation); ZVAL_STRING(compilation, "", 1); /** * Evaluate common expressions */ PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); /** * Foreach statement */ PHALCON_OBS_VAR(variable); phalcon_array_fetch_string(&variable, statement, SL("variable"), PH_NOISY_CC); /** * Check if a 'key' variable needs to be calculated */ if (phalcon_array_isset_string(statement, SS("key"))) { PHALCON_OBS_VAR(key); phalcon_array_fetch_string(&key, statement, SL("key"), PH_NOISY_CC); PHALCON_SCONCAT_SVSVSVS(compilation, "<?php foreach (", expr_code, " as $", key, " => $", variable, ") { "); } else { PHALCON_SCONCAT_SVSVS(compilation, "<?php foreach (", expr_code, " as $", variable, ") { "); } /** * Check for an 'if' expr in the block */ if (phalcon_array_isset_string(statement, SS("if_expr"))) { PHALCON_OBS_VAR(if_expr); phalcon_array_fetch_string(&if_expr, statement, SL("if_expr"), PH_NOISY_CC); PHALCON_INIT_VAR(if_expr_code); PHALCON_CALL_METHOD_PARAMS_1(if_expr_code, this_ptr, "expression", if_expr); PHALCON_SCONCAT_SVS(compilation, "if (", if_expr_code, ") { ?>"); } else { phalcon_concat_self_str(&compilation, SL("?>") TSRMLS_CC); } /** * Process the block statements */ PHALCON_OBS_VAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("block_statements"), PH_NOISY_CC); PHALCON_INIT_VAR(code); PHALCON_CALL_METHOD_PARAMS_2(code, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_concat_self(&compilation, code TSRMLS_CC); if (phalcon_array_isset_string(statement, SS("if_expr"))) { phalcon_concat_self_str(&compilation, SL("<?php } } ?>") TSRMLS_CC); } else { phalcon_concat_self_str(&compilation, SL("<?php } ?>") TSRMLS_CC); } RETURN_CTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileIf){ zval *statement, *extends_mode = NULL, *compilation; zval *expr, *expr_code, *block_statements = NULL, *code = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &statement, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } PHALCON_INIT_VAR(compilation); /** * Evaluate common expressions */ if (phalcon_array_isset_string(statement, SS("expr"))) { PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); } /** * 'If' statement */ PHALCON_SCONCAT_SVS(compilation, "<?php if (", expr_code, ") { ?>"); PHALCON_OBS_VAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("true_statements"), PH_NOISY_CC); /** * Process statements in the 'true' block */ PHALCON_INIT_VAR(code); PHALCON_CALL_METHOD_PARAMS_2(code, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_concat_self(&compilation, code TSRMLS_CC); /** * Check for a 'else'/'elseif' block */ if (phalcon_array_isset_string(statement, SS("false_statements"))) { phalcon_concat_self_str(&compilation, SL("<?php } else { ?>") TSRMLS_CC); /** * Process statements in the 'false' block */ PHALCON_OBS_NVAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("false_statements"), PH_NOISY_CC); PHALCON_INIT_NVAR(code); PHALCON_CALL_METHOD_PARAMS_2(code, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_concat_self(&compilation, code TSRMLS_CC); } phalcon_concat_self_str(&compilation, SL("<?php } ?>") TSRMLS_CC); RETURN_CCTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileElseIf){ zval *statement, *expr, *expr_code, *compilation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statement) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); /** * 'elseif' statement */ PHALCON_INIT_VAR(compilation); PHALCON_CONCAT_SVS(compilation, "<?php } elseif (", expr_code, ") { ?>"); RETURN_CTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileCache){ zval *statement, *extends_mode = NULL, *compilation; zval *expr, *expr_code, *block_statements, *code; zval *lifetime; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &statement, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } PHALCON_INIT_VAR(compilation); /** * Evaluate common expressions */ PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); /** * Cache statement */ PHALCON_SCONCAT_SVS(compilation, "<?php $_cache[", expr_code, "] = $this->di->get('viewCache'); "); PHALCON_SCONCAT_SVSVSVS(compilation, "$_cacheKey[", expr_code, "] = $_cache[", expr_code, "]->start(", expr_code, "); "); PHALCON_SCONCAT_SVS(compilation, "if ($_cacheKey[", expr_code, "] === null) { ?>"); /** * Get the code in the block */ PHALCON_OBS_VAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("block_statements"), PH_NOISY_CC); PHALCON_INIT_VAR(code); PHALCON_CALL_METHOD_PARAMS_2(code, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_concat_self(&compilation, code TSRMLS_CC); /** * Check if the cache has a lifetime */ if (phalcon_array_isset_string(statement, SS("lifetime"))) { PHALCON_OBS_VAR(lifetime); phalcon_array_fetch_string(&lifetime, statement, SL("lifetime"), PH_NOISY_CC); PHALCON_SCONCAT_SVSVSVS(compilation, "<?php $_cache[", expr_code, "]->save(", expr_code, ", null, ", lifetime, "); "); PHALCON_SCONCAT_SVS(compilation, "} else { echo $_cacheKey[", expr_code, "]; } ?>"); } else { PHALCON_SCONCAT_SVSVSVS(compilation, "<?php $_cache[", expr_code, "]->save(", expr_code, "); } else { echo $_cacheKey[", expr_code, "]; } ?>"); } RETURN_CCTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileEcho){ zval *statement, *compilation, *expr, *expr_code; zval *expr_type, *name, *name_type, *name_value; zval *autoescape; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statement) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(compilation); /** * Evaluate common expressions */ PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); PHALCON_OBS_VAR(expr_type); phalcon_array_fetch_string(&expr_type, expr, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(expr_type, 350)) { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, expr, SL("name"), PH_NOISY_CC); PHALCON_OBS_VAR(name_type); phalcon_array_fetch_string(&name_type, name, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(name_type, 265)) { PHALCON_OBS_VAR(name_value); phalcon_array_fetch_string(&name_value, name, SL("value"), PH_NOISY_CC); /** * super() is a function however the return of this function must be output as it * is */ if (PHALCON_IS_STRING(name_value, "super")) { RETURN_CCTOR(expr_code); } } } /** * Echo statement */ PHALCON_OBS_VAR(autoescape); phalcon_read_property(&autoescape, this_ptr, SL("_autoescape"), PH_NOISY_CC); if (zend_is_true(autoescape)) { PHALCON_SCONCAT_SVS(compilation, "<?php echo $this->escaper->escapeHtml(", expr_code, "); ?>"); } else { PHALCON_SCONCAT_SVS(compilation, "<?php echo ", expr_code, "; ?>"); } RETURN_CCTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileInclude){ zval *statement, *compilation = NULL, *path, *view, *views_dir; zval *final_path = NULL, *extended, *sub_compiler, *compiled_path; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statement) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(compilation); ZVAL_STRING(compilation, "", 1); /** * Include statement */ PHALCON_OBS_VAR(path); phalcon_array_fetch_string(&path, statement, SL("path"), PH_NOISY_CC); PHALCON_OBS_VAR(view); phalcon_read_property(&view, this_ptr, SL("_view"), PH_NOISY_CC); if (Z_TYPE_P(view) == IS_OBJECT) { PHALCON_INIT_VAR(views_dir); PHALCON_CALL_METHOD(views_dir, view, "getviewsdir"); PHALCON_INIT_VAR(final_path); PHALCON_CONCAT_VV(final_path, views_dir, path); } else { PHALCON_CPY_WRT(final_path, path); } /** * Perform a subcompilation of the included file */ PHALCON_INIT_VAR(extended); ZVAL_BOOL(extended, 0); PHALCON_INIT_VAR(sub_compiler); if (phalcon_clone(sub_compiler, this_ptr TSRMLS_CC) == FAILURE) { return; } PHALCON_INIT_NVAR(compilation); PHALCON_CALL_METHOD_PARAMS_2(compilation, sub_compiler, "compile", final_path, extended); /** * If the compilation doesn't return anything we include the compiled path */ if (Z_TYPE_P(compilation) == IS_NULL) { PHALCON_INIT_VAR(compiled_path); PHALCON_CALL_METHOD(compiled_path, sub_compiler, "getcompiledtemplatepath"); PHALCON_INIT_NVAR(compilation); PHALCON_CALL_FUNC_PARAMS_1(compilation, "file_get_contents", compiled_path); } RETURN_CCTOR(compilation); } /** * */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileSet){ zval *statement, *expr, *expr_code, *variable, *compilation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statement) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); /** * Set statement */ PHALCON_OBS_VAR(variable); phalcon_array_fetch_string(&variable, statement, SL("variable"), PH_NOISY_CC); PHALCON_INIT_VAR(compilation); PHALCON_CONCAT_SVSVS(compilation, "<?php $", variable, " = ", expr_code, "; ?>"); RETURN_CTOR(compilation); } /** * */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileDo){ zval *statement, *expr, *expr_code, *compilation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &statement) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(expr); phalcon_array_fetch_string(&expr, statement, SL("expr"), PH_NOISY_CC); PHALCON_INIT_VAR(expr_code); PHALCON_CALL_METHOD_PARAMS_1(expr_code, this_ptr, "expression", expr); PHALCON_INIT_VAR(compilation); PHALCON_CONCAT_SVS(compilation, "<?php ", expr_code, "; ?>"); RETURN_CTOR(compilation); } PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileAutoEscape){ zval *statement, *extends_mode, *old_autoescape; zval *autoescape, *block_statements, *compilation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &statement, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(old_autoescape); phalcon_read_property(&old_autoescape, this_ptr, SL("_autoescape"), PH_NOISY_CC); PHALCON_OBS_VAR(autoescape); phalcon_array_fetch_string(&autoescape, statement, SL("enable"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_autoescape"), autoescape TSRMLS_CC); PHALCON_OBS_VAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("block_statements"), PH_NOISY_CC); PHALCON_INIT_VAR(compilation); PHALCON_CALL_METHOD_PARAMS_2(compilation, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_update_property_zval(this_ptr, SL("_autoescape"), old_autoescape TSRMLS_CC); RETURN_CCTOR(compilation); } /** * Traverses a statement list compiling each of its nodes * * @param array $statement * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementList){ zval *statements, *extends_mode = NULL, *extended = NULL, *block_mode = NULL; zval *compilation = NULL, *statement = NULL, *line = NULL, *file = NULL, *exception_message = NULL; zval *type = NULL, *temp_compilation = NULL, *block_name = NULL, *block_statements = NULL; zval *blocks = NULL, *code = NULL, *path = NULL, *view = NULL, *views_dir = NULL, *final_path = NULL; zval *sub_compiler = NULL, *compiled_path = NULL, *level; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &statements, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } /** * Nothing to compile */ if (!phalcon_fast_count_ev(statements TSRMLS_CC)) { PHALCON_MM_RESTORE(); RETURN_EMPTY_STRING(); } /** * Increase the statement recursion level in extends mode */ PHALCON_OBS_VAR(extended); phalcon_read_property(&extended, this_ptr, SL("_extended"), PH_NOISY_CC); PHALCON_INIT_VAR(block_mode); ZVAL_BOOL(block_mode, zend_is_true(extended) || zend_is_true(extends_mode)); if (PHALCON_IS_TRUE(block_mode)) { phalcon_property_incr(this_ptr, SL("_level") TSRMLS_CC); } PHALCON_INIT_VAR(compilation); if (!phalcon_is_iterable(statements, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(statement); /** * All statements must be arrays */ if (Z_TYPE_P(statement) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Corrupted statement"); return; } /** * Check if the statement is valid */ if (!phalcon_array_isset_string(statement, SS("type"))) { PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, statement, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, statement, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSV(exception_message, "Invalid statement in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, statement, SL("type"), PH_NOISY_CC); switch (phalcon_get_intval(type)) { case 357: /** * Raw output statement */ PHALCON_OBS_NVAR(temp_compilation); phalcon_array_fetch_string(&temp_compilation, statement, SL("value"), PH_NOISY_CC); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 300: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_2(temp_compilation, this_ptr, "compileif", statement, extends_mode); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 302: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_1(temp_compilation, this_ptr, "compileelseif", statement); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 304: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_2(temp_compilation, this_ptr, "compileforeach", statement, extends_mode); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 306: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_1(temp_compilation, this_ptr, "compileset", statement); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; break; case 359: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_1(temp_compilation, this_ptr, "compileecho", statement); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 307: /** * Block statement */ PHALCON_OBS_NVAR(block_name); phalcon_array_fetch_string(&block_name, statement, SL("name"), PH_NOISY_CC); if (phalcon_array_isset_string(statement, SS("block_statements"))) { PHALCON_OBS_NVAR(block_statements); phalcon_array_fetch_string(&block_statements, statement, SL("block_statements"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(block_statements); } PHALCON_OBS_NVAR(blocks); phalcon_read_property(&blocks, this_ptr, SL("_blocks"), PH_NOISY_CC); if (zend_is_true(block_mode)) { if (Z_TYPE_P(blocks) != IS_ARRAY) { PHALCON_INIT_NVAR(blocks); array_init(blocks); } /** * Create a unamed block */ if (Z_TYPE_P(compilation) != IS_NULL) { phalcon_array_append(&blocks, compilation, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(compilation); } /** * In extends mode we add the block statements to the blocks variable */ phalcon_array_update_zval(&blocks, block_name, &block_statements, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_blocks"), blocks TSRMLS_CC); } else { if (Z_TYPE_P(block_statements) == IS_ARRAY) { PHALCON_INIT_NVAR(code); PHALCON_CALL_METHOD_PARAMS_2(code, this_ptr, "_statementlist", block_statements, extends_mode); phalcon_concat_self(&compilation, code TSRMLS_CC); } } break; case 310: /** * Extends statement */ PHALCON_OBS_NVAR(path); phalcon_array_fetch_string(&path, statement, SL("path"), PH_NOISY_CC); PHALCON_OBS_NVAR(view); phalcon_read_property(&view, this_ptr, SL("_view"), PH_NOISY_CC); if (Z_TYPE_P(view) == IS_OBJECT) { PHALCON_INIT_NVAR(views_dir); PHALCON_CALL_METHOD(views_dir, view, "getviewsdir"); PHALCON_INIT_NVAR(final_path); PHALCON_CONCAT_VV(final_path, views_dir, path); } else { PHALCON_CPY_WRT(final_path, path); } PHALCON_INIT_NVAR(extended); ZVAL_BOOL(extended, 1); /** * Perform a subcompilation of the extended file */ PHALCON_INIT_NVAR(sub_compiler); if (phalcon_clone(sub_compiler, this_ptr TSRMLS_CC) == FAILURE) { return; } PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_2(temp_compilation, sub_compiler, "compile", final_path, extended); /** * If the compilation doesn't return anything we include the compiled path */ if (Z_TYPE_P(temp_compilation) == IS_NULL) { PHALCON_INIT_NVAR(compiled_path); PHALCON_CALL_METHOD(compiled_path, sub_compiler, "getcompiledtemplatepath"); PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_FUNC_PARAMS_1(temp_compilation, "file_get_contents", compiled_path); } phalcon_update_property_bool(this_ptr, SL("_extended"), 1 TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_extendedBlocks"), temp_compilation TSRMLS_CC); PHALCON_CPY_WRT(block_mode, extended); break; case 313: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_1(temp_compilation, this_ptr, "compileinclude", statement); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 314: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_2(temp_compilation, this_ptr, "compilecache", statement, extends_mode); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 316: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_1(temp_compilation, this_ptr, "compiledo", statement); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 317: PHALCON_INIT_NVAR(temp_compilation); PHALCON_CALL_METHOD_PARAMS_2(temp_compilation, this_ptr, "compileautoescape", statement, extends_mode); phalcon_concat_self(&compilation, temp_compilation TSRMLS_CC); break; case 319: phalcon_concat_self_str(&compilation, SL("<?php continue; ?>") TSRMLS_CC); break; case 320: phalcon_concat_self_str(&compilation, SL("<?php break; ?>") TSRMLS_CC); break; default: PHALCON_OBS_NVAR(line); phalcon_array_fetch_string(&line, statement, SL("line"), PH_NOISY_CC); PHALCON_OBS_NVAR(file); phalcon_array_fetch_string(&file, statement, SL("file"), PH_NOISY_CC); PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVSV(exception_message, "Unknown statement ", type, " in ", file, " on line ", line); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } zend_hash_move_forward_ex(ah0, &hp0); } /** * Reduce the statement level nesting */ if (PHALCON_IS_TRUE(block_mode)) { PHALCON_OBS_VAR(level); phalcon_read_property(&level, this_ptr, SL("_level"), PH_NOISY_CC); if (PHALCON_IS_LONG(level, 1)) { if (Z_TYPE_P(compilation) != IS_NULL) { phalcon_update_property_array_append(this_ptr, SL("_blocks"), compilation TSRMLS_CC); } } phalcon_property_decr(this_ptr, SL("_level") TSRMLS_CC); } RETURN_CCTOR(compilation); } /** * Compiles a Volt source code returning a PHP plain version * * @param string $viewCode * @param boolean $extendsMode * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _compileSource){ zval *view_code, *extends_mode = NULL, *current_path; zval *intermediate, *compilation, *extended; zval *final_compilation = NULL, *blocks = NULL, *extended_blocks; zval *block = NULL, *name = NULL, *local_block = NULL, *block_compilation = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &view_code, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } PHALCON_OBS_VAR(current_path); phalcon_read_property(&current_path, this_ptr, SL("_currentPath"), PH_NOISY_CC); PHALCON_INIT_VAR(intermediate); if (phvolt_parse_view(intermediate, view_code, current_path TSRMLS_CC) == FAILURE) { return; } /** * The parsing must return a valid array */ if (Z_TYPE_P(intermediate) == IS_ARRAY) { PHALCON_INIT_VAR(compilation); PHALCON_CALL_METHOD_PARAMS_2(compilation, this_ptr, "_statementlist", intermediate, extends_mode); /** * Check if the template is extending another */ PHALCON_OBS_VAR(extended); phalcon_read_property(&extended, this_ptr, SL("_extended"), PH_NOISY_CC); if (PHALCON_IS_TRUE(extended)) { /** * Multiple-Inheritance is allowed */ if (PHALCON_IS_TRUE(extends_mode)) { PHALCON_INIT_VAR(final_compilation); array_init(final_compilation); } else { PHALCON_INIT_NVAR(final_compilation); } PHALCON_OBS_VAR(blocks); phalcon_read_property(&blocks, this_ptr, SL("_blocks"), PH_NOISY_CC); PHALCON_OBS_VAR(extended_blocks); phalcon_read_property(&extended_blocks, this_ptr, SL("_extendedBlocks"), PH_NOISY_CC); if (!phalcon_is_iterable(extended_blocks, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(name, ah0, hp0); PHALCON_GET_FOREACH_VALUE(block); /** * If name is a string then is a block name */ if (Z_TYPE_P(name) == IS_STRING) { if (Z_TYPE_P(block) == IS_ARRAY) { if (phalcon_array_isset(blocks, name)) { /** * The block is set in the local template */ PHALCON_OBS_NVAR(local_block); phalcon_array_fetch(&local_block, blocks, name, PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_currentBlock"), name TSRMLS_CC); PHALCON_INIT_NVAR(block_compilation); PHALCON_CALL_METHOD_PARAMS_1(block_compilation, this_ptr, "_statementlist", local_block); } else { /** * The block is not set local only in the extended template */ PHALCON_INIT_NVAR(block_compilation); PHALCON_CALL_METHOD_PARAMS_1(block_compilation, this_ptr, "_statementlist", block); } } else { if (phalcon_array_isset(blocks, name)) { /** * The block is set in the local template */ PHALCON_OBS_NVAR(local_block); phalcon_array_fetch(&local_block, blocks, name, PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_currentBlock"), name TSRMLS_CC); PHALCON_INIT_NVAR(block_compilation); PHALCON_CALL_METHOD_PARAMS_1(block_compilation, this_ptr, "_statementlist", local_block); } else { PHALCON_INIT_NVAR(block_compilation); } } if (PHALCON_IS_TRUE(extends_mode)) { phalcon_array_update_zval(&final_compilation, name, &block_compilation, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_concat_self(&final_compilation, block_compilation TSRMLS_CC); } } else { /** * Here the block is an already compiled text */ if (PHALCON_IS_TRUE(extends_mode)) { phalcon_array_append(&final_compilation, block, PH_SEPARATE TSRMLS_CC); } else { phalcon_concat_self(&final_compilation, block TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CCTOR(final_compilation); } if (PHALCON_IS_TRUE(extends_mode)) { /** * In extends mode we return the template blocks instead of the compilation */ PHALCON_OBS_NVAR(blocks); phalcon_read_property(&blocks, this_ptr, SL("_blocks"), PH_NOISY_CC); RETURN_CCTOR(blocks); } RETURN_CCTOR(compilation); } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Invalid intermediate representation"); return; } /** * Compiles a template into a string * *<code> * echo $compiler->compileString('{{ "hello world" }}'); *</code> * * @param string $viewCode * @param boolean $extendsMode * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileString){ zval *view_code, *extends_mode = NULL, *current_path; zval *compilation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &view_code, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } if (Z_TYPE_P(view_code) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "The code must be string"); return; } PHALCON_INIT_VAR(current_path); ZVAL_STRING(current_path, "eval code", 1); phalcon_update_property_zval(this_ptr, SL("_currentPath"), current_path TSRMLS_CC); PHALCON_INIT_VAR(compilation); PHALCON_CALL_METHOD_PARAMS_2(compilation, this_ptr, "_compilesource", view_code, extends_mode); RETURN_CCTOR(compilation); } /** * Compiles a template into a file forcing the destination path * *<code> * $compiler->compile('views/layouts/main.volt', 'views/layouts/main.volt.php'); *</code> * * @param string $path * @param string $compiledPath * @param boolean $extendsMode * @return string|array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileFile){ zval *path, *compiled_path, *extends_mode = NULL, *view_code; zval *exception_message, *compilation, *final_compilation = NULL; zval *status; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &path, &compiled_path, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } if (PHALCON_IS_EQUAL(path, compiled_path)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Template path and compilation template path cannot be the same"); return; } /** * Always use file_get_contents instead of read the file directly, this respect the * open_basedir directive */ PHALCON_INIT_VAR(view_code); PHALCON_CALL_FUNC_PARAMS_1(view_code, "file_get_contents", path); if (PHALCON_IS_FALSE(view_code)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Template file ", path, " could not be opened"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } phalcon_update_property_zval(this_ptr, SL("_currentPath"), path TSRMLS_CC); PHALCON_INIT_VAR(compilation); PHALCON_CALL_METHOD_PARAMS_2(compilation, this_ptr, "_compilesource", view_code, extends_mode); /** * We store the file serialized if it's an array of blocks */ if (Z_TYPE_P(compilation) == IS_ARRAY) { PHALCON_INIT_VAR(final_compilation); PHALCON_CALL_FUNC_PARAMS_1(final_compilation, "serialize", compilation); } else { PHALCON_CPY_WRT(final_compilation, compilation); } /** * Always use file_put_contents to write files instead of write the file directly, * this respect the open_basedir directive */ PHALCON_INIT_VAR(status); PHALCON_CALL_FUNC_PARAMS_2(status, "file_put_contents", compiled_path, final_compilation); if (PHALCON_IS_FALSE(status)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "Volt directory can't be written"); return; } RETURN_CCTOR(compilation); } /** * Compiles a template into a file applying the compiler options * This method does not return the compiled path if the template was not compiled * *<code> * $compiler->compile('views/layouts/main.volt'); * require $compiler->getCompiledTemplatePath(); *</code> * * @param string $templatePath * @param boolean $extendsMode * @return string|array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compile){ zval *template_path, *extends_mode = NULL, *stat = NULL, *compile_always = NULL; zval *compiled_path = NULL, *prefix = NULL, *compiled_separator = NULL; zval *compiled_extension = NULL, *compilation = NULL, *options; zval *template_sep_path = NULL, *compiled_template_path = NULL; zval *blocks_code, *exception_message = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &template_path, &extends_mode) == FAILURE) { RETURN_MM_NULL(); } if (!extends_mode) { PHALCON_INIT_VAR(extends_mode); ZVAL_BOOL(extends_mode, 0); } /** * Re-initialize some properties already initialized when the object is cloned */ phalcon_update_property_bool(this_ptr, SL("_extended"), 0 TSRMLS_CC); phalcon_update_property_bool(this_ptr, SL("_extendedBlocks"), 0 TSRMLS_CC); phalcon_update_property_null(this_ptr, SL("_blocks") TSRMLS_CC); phalcon_update_property_long(this_ptr, SL("_level"), 0 TSRMLS_CC); phalcon_update_property_long(this_ptr, SL("_exprLevel"), 0 TSRMLS_CC); PHALCON_INIT_VAR(stat); ZVAL_BOOL(stat, 1); PHALCON_INIT_VAR(compile_always); ZVAL_BOOL(compile_always, 0); PHALCON_INIT_VAR(compiled_path); PHALCON_INIT_VAR(prefix); PHALCON_INIT_VAR(compiled_separator); ZVAL_STRING(compiled_separator, "%%", 1); PHALCON_INIT_VAR(compiled_extension); ZVAL_STRING(compiled_extension, ".php", 1); PHALCON_INIT_VAR(compilation); PHALCON_OBS_VAR(options); phalcon_read_property(&options, this_ptr, SL("_options"), PH_NOISY_CC); if (Z_TYPE_P(options) == IS_ARRAY) { /** * This makes that templates will be compiled always */ if (phalcon_array_isset_string(options, SS("compileAlways"))) { PHALCON_OBS_NVAR(compile_always); phalcon_array_fetch_string(&compile_always, options, SL("compileAlways"), PH_NOISY_CC); if (Z_TYPE_P(compile_always) != IS_BOOL) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "compileAlways must be a bool value"); return; } } /** * Prefix is prepended to the template name */ if (phalcon_array_isset_string(options, SS("prefix"))) { PHALCON_OBS_NVAR(prefix); phalcon_array_fetch_string(&prefix, options, SL("prefix"), PH_NOISY_CC); if (Z_TYPE_P(prefix) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "prefix must be a string"); return; } } /** * Compiled path is a directory where the compiled templates will be located */ if (phalcon_array_isset_string(options, SS("compiledPath"))) { PHALCON_OBS_NVAR(compiled_path); phalcon_array_fetch_string(&compiled_path, options, SL("compiledPath"), PH_NOISY_CC); if (Z_TYPE_P(compiled_path) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "compiledPath must be a string"); return; } } /** * There is no compiled separator by default */ if (phalcon_array_isset_string(options, SS("compiledSeparator"))) { PHALCON_OBS_NVAR(compiled_separator); phalcon_array_fetch_string(&compiled_separator, options, SL("compiledSeparator"), PH_NOISY_CC); if (Z_TYPE_P(compiled_separator) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "compiledSeparator must be a string"); return; } } /** * By default the compile extension is .php */ if (phalcon_array_isset_string(options, SS("compiledExtension"))) { PHALCON_OBS_NVAR(compiled_extension); phalcon_array_fetch_string(&compiled_extension, options, SL("compiledExtension"), PH_NOISY_CC); if (Z_TYPE_P(compiled_extension) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_view_exception_ce, "compiledExtension must be a string"); return; } } /** * Stat option assumes the compilation of the file */ if (phalcon_array_isset_string(options, SS("stat"))) { PHALCON_OBS_NVAR(stat); phalcon_array_fetch_string(&stat, options, SL("stat"), PH_NOISY_CC); } } if (Z_TYPE_P(compiled_path) != IS_NULL) { /** * Create the virtual path replacing the directory separator by the compiled * separator */ PHALCON_INIT_VAR(template_sep_path); phalcon_prepare_virtual_path(template_sep_path, template_path, compiled_separator TSRMLS_CC); } else { PHALCON_CPY_WRT(template_sep_path, template_path); } /** * In extends mode we add an additional 'e' suffix to the file */ if (PHALCON_IS_TRUE(extends_mode)) { PHALCON_INIT_VAR(compiled_template_path); PHALCON_CONCAT_VVVVSVV(compiled_template_path, compiled_path, prefix, template_sep_path, compiled_separator, "e", compiled_separator, compiled_extension); } else { PHALCON_INIT_NVAR(compiled_template_path); PHALCON_CONCAT_VVVV(compiled_template_path, compiled_path, prefix, template_sep_path, compiled_extension); } if (zend_is_true(compile_always)) { /** * Compile always must be used only in the development stage */ PHALCON_CALL_METHOD_PARAMS_3(compilation, this_ptr, "compilefile", template_path, compiled_template_path, extends_mode); } else { if (PHALCON_IS_TRUE(stat)) { if (phalcon_file_exists(compiled_template_path TSRMLS_CC) == SUCCESS) { /** * Compare modification timestamps to check if the file needs to be recompiled */ if (phalcon_compare_mtime(template_path, compiled_template_path TSRMLS_CC)) { PHALCON_INIT_NVAR(compilation); PHALCON_CALL_METHOD_PARAMS_3(compilation, this_ptr, "compilefile", template_path, compiled_template_path, extends_mode); } else { if (PHALCON_IS_TRUE(extends_mode)) { /** * In extends mode we read the file that must contains a serialized array of blocks */ PHALCON_INIT_VAR(blocks_code); PHALCON_CALL_FUNC_PARAMS_1(blocks_code, "file_get_contents", compiled_template_path); if (PHALCON_IS_FALSE(blocks_code)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Extends compilation file ", compiled_template_path, " could not be opened"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } /** * Unserialize the array blocks code */ if (zend_is_true(blocks_code)) { PHALCON_INIT_NVAR(compilation); PHALCON_CALL_FUNC_PARAMS_1(compilation, "unserialize", blocks_code); } else { PHALCON_INIT_NVAR(compilation); array_init(compilation); } } } } else { /** * The file doesn't exist so we compile the php version for the first time */ PHALCON_INIT_NVAR(compilation); PHALCON_CALL_METHOD_PARAMS_3(compilation, this_ptr, "compilefile", template_path, compiled_template_path, extends_mode); } } else { /** * Stat is off but the compiled file doesn't exist */ if (phalcon_file_exists(compiled_template_path TSRMLS_CC) == FAILURE) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Compiled template file ", compiled_template_path, " does not exist"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_view_exception_ce, exception_message); return; } } } phalcon_update_property_zval(this_ptr, SL("_compiledTemplatePath"), compiled_template_path TSRMLS_CC); RETURN_CCTOR(compilation); } /** * Returns the path to the last compiled template * * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getCompiledTemplatePath){ RETURN_MEMBER(this_ptr, "_compiledTemplatePath"); } /** * Parses a Volt template returning its intermediate representation * *<code> * print_r($compiler->parse('{{ 3 + 2 }}')); *</code> * * @param string $viewCode * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, parse){ zval *view_code, *current_path, *intermediate; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &view_code) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(current_path); ZVAL_STRING(current_path, "eval code", 1); PHALCON_INIT_VAR(intermediate); if (phvolt_parse_view(intermediate, view_code, current_path TSRMLS_CC) == FAILURE) { return; } RETURN_CTOR(intermediate); }
tmihalik/cphalcon
ext/mvc/model/query.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/exception.h" #include "kernel/fcall.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/operators.h" #include "kernel/string.h" #include "kernel/file.h" #include "mvc/model/query/scanner.h" #include "mvc/model/query/phql.h" /** * Phalcon\Mvc\Model\Query * * This class takes a PHQL intermediate representation and executes it. * *<code> * * $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b * WHERE b.name = :name: ORDER BY c.name"; * * $result = $manager->executeQuery($phql, array( * 'name' => 'Lamborghini' * )); * * foreach ($result as $row) { * echo "Name: ", $row->cars->name, "\n"; * echo "Price: ", $row->cars->price, "\n"; * echo "Taxes: ", $row->taxes, "\n"; * } * *</code> * */ /** * Phalcon\Mvc\Model\Query initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Query){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc\\Model, Query, mvc_model_query, phalcon_mvc_model_query_method_entry, 0); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_manager"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_metaData"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_type"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_phql"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_ast"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_intermediate"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_models"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_sqlAliases"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_sqlAliasesModels"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_sqlModelsAliases"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_sqlAliasesModelsInstances"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_sqlColumnAliases"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_modelsInstances"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_cache"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_cacheOptions"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_query_ce, SL("_uniqueRow"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_query_ce, SL("TYPE_SELECT"), 309 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_query_ce, SL("TYPE_INSERT"), 306 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_query_ce, SL("TYPE_UPDATE"), 300 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_query_ce, SL("TYPE_DELETE"), 303 TSRMLS_CC); zend_class_implements(phalcon_mvc_model_query_ce TSRMLS_CC, 2, phalcon_mvc_model_queryinterface_ce, phalcon_di_injectionawareinterface_ce); return SUCCESS; } /** * Phalcon\Mvc\Model\Query constructor * * @param string $phql */ PHP_METHOD(Phalcon_Mvc_Model_Query, __construct){ zval *phql = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &phql) == FAILURE) { RETURN_MM_NULL(); } if (!phql) { PHALCON_INIT_VAR(phql); } if (Z_TYPE_P(phql) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_phql"), phql TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Sets the dependency injection container * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_Model_Query, setDI){ zval *dependency_injector, *service = NULL, *manager; zval *meta_data; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the ORM services"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "modelsManager", 1); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD_PARAMS_1(manager, dependency_injector, "getshared", service); if (Z_TYPE_P(manager) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Injected service 'modelsManager' is invalid"); return; } PHALCON_INIT_NVAR(service); ZVAL_STRING(service, "modelsMetadata", 1); PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD_PARAMS_1(meta_data, dependency_injector, "getshared", service); if (Z_TYPE_P(meta_data) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Injected service 'modelsMetadata' is invalid"); return; } phalcon_update_property_zval(this_ptr, SL("_manager"), manager TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_metaData"), meta_data TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the dependency injection container * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Tells to the query if only the first row in the resultset must be resturned * * @param boolean $uniqueRow * @return Phalcon\Mvc\Model\Query */ PHP_METHOD(Phalcon_Mvc_Model_Query, setUniqueRow){ zval *unique_row; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &unique_row) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_uniqueRow"), unique_row TSRMLS_CC); RETURN_THISW(); } /** * Check if the query is programmed to get only the first row in the resultset * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model_Query, getUniqueRow){ RETURN_MEMBER(this_ptr, "_uniqueRow"); } /** * Replaces the model's name to its source name in a qualifed-name expression * * @param array $expr * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getQualified){ zval *expr, *column_name, *sql_column_aliases; zval *source_column = NULL, *meta_data, *column_domain; zval *sql_aliases, *exception_message = NULL, *source = NULL; zval *sql_aliases_models_instances, *model = NULL; zval *column_map = NULL, *real_column_name = NULL, *one, *number; zval *has_model = NULL, *models_instances, *has_attribute = NULL; zval *ambiguity = NULL, *models, *class_name; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &expr) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(column_name); phalcon_array_fetch_string(&column_name, expr, SL("name"), PH_NOISY_CC); /** * Check if the qualified name is a column alias */ PHALCON_OBS_VAR(sql_column_aliases); phalcon_read_property(&sql_column_aliases, this_ptr, SL("_sqlColumnAliases"), PH_NOISY_CC); if (phalcon_array_isset(sql_column_aliases, column_name)) { PHALCON_INIT_VAR(source_column); array_init_size(source_column, 2); add_assoc_stringl_ex(source_column, SS("type"), SL("qualified"), 1); phalcon_array_update_string(&source_column, SL("name"), &column_name, PH_COPY | PH_SEPARATE TSRMLS_CC); RETURN_CTOR(source_column); } PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC); /** * Check if the qualified name has a domain */ if (phalcon_array_isset_string(expr, SS("domain"))) { PHALCON_OBS_VAR(column_domain); phalcon_array_fetch_string(&column_domain, expr, SL("domain"), PH_NOISY_CC); PHALCON_OBS_VAR(sql_aliases); phalcon_read_property(&sql_aliases, this_ptr, SL("_sqlAliases"), PH_NOISY_CC); /** * The column has a domain, we need to check if it's an alias */ if (!phalcon_array_isset(sql_aliases, column_domain)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Unknown table or alias '", column_domain, "' (1)"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_OBS_VAR(source); phalcon_array_fetch(&source, sql_aliases, column_domain, PH_NOISY_CC); /** * Retrieve the corresponding model by its alias */ PHALCON_OBS_VAR(sql_aliases_models_instances); phalcon_read_property(&sql_aliases_models_instances, this_ptr, SL("_sqlAliasesModelsInstances"), PH_NOISY_CC); if (!phalcon_array_isset(sql_aliases_models_instances, column_domain)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "There is no model related to table or alias '", column_domain, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Change the selected column by its real name on its mapped table */ if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_OBS_VAR(model); phalcon_array_fetch(&model, sql_aliases_models_instances, column_domain, PH_NOISY_CC); PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getreversecolumnmap", model); } else { PHALCON_INIT_NVAR(column_map); } if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, column_name)) { PHALCON_OBS_VAR(real_column_name); phalcon_array_fetch(&real_column_name, column_map, column_name, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "Column '", column_name, "' doesn't belong to the model or alias '", column_domain, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(real_column_name, column_name); } } else { /** * If the column IR doesn't have a domain, we must check for ambiguities */ PHALCON_INIT_VAR(one); ZVAL_LONG(one, 1); PHALCON_INIT_VAR(number); ZVAL_LONG(number, 0); PHALCON_INIT_VAR(has_model); ZVAL_BOOL(has_model, 0); PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); if (!phalcon_is_iterable(models_instances, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(model); PHALCON_INIT_NVAR(has_attribute); PHALCON_CALL_METHOD_PARAMS_2(has_attribute, meta_data, "hasattribute", model, column_name); if (zend_is_true(has_attribute)) { PHALCON_SEPARATE(number); increment_function(number); PHALCON_INIT_NVAR(ambiguity); is_smaller_function(ambiguity, one, number TSRMLS_CC); if (PHALCON_IS_TRUE(ambiguity)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "The column '", column_name, "' is ambiguous"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_CPY_WRT(has_model, model); } zend_hash_move_forward_ex(ah0, &hp0); } if (PHALCON_IS_FALSE(has_model)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", column_name, "' doesn't belong to any of the selected models (1)"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Check if the _models property is correctly prepared */ PHALCON_OBS_VAR(models); phalcon_read_property(&models, this_ptr, SL("_models"), PH_NOISY_CC); if (Z_TYPE_P(models) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The models list was not loaded correctly"); return; } /** * Obtain the model's source from the _models list */ PHALCON_INIT_VAR(class_name); phalcon_get_class(class_name, has_model, 0 TSRMLS_CC); if (phalcon_array_isset(models, class_name)) { PHALCON_OBS_NVAR(source); phalcon_array_fetch(&source, models, class_name, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", column_name, "' doesn't belong to any of the selected models (2)"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Rename the column */ if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_NVAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getreversecolumnmap", has_model); } else { PHALCON_INIT_NVAR(column_map); } if (Z_TYPE_P(column_map) == IS_ARRAY) { /** * The real column name is in the column map */ if (phalcon_array_isset(column_map, column_name)) { PHALCON_OBS_NVAR(real_column_name); phalcon_array_fetch(&real_column_name, column_map, column_name, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", column_name, "' doesn't belong to any of the selected models (3)"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(real_column_name, column_name); } } /** * Create an array with the qualified info */ PHALCON_INIT_NVAR(source_column); array_init_size(source_column, 4); add_assoc_stringl_ex(source_column, SS("type"), SL("qualified"), 1); phalcon_array_update_string(&source_column, SL("domain"), &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&source_column, SL("name"), &real_column_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&source_column, SL("balias"), &column_name, PH_COPY | PH_SEPARATE TSRMLS_CC); RETURN_CTOR(source_column); } /** * Resolves a expression in a single call argument * * @param array $argument * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getCallArgument){ zval *argument, *argument_type, *argument_expr = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &argument) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(argument_type); phalcon_array_fetch_string(&argument_type, argument, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(argument_type, 352)) { PHALCON_INIT_VAR(argument_expr); array_init_size(argument_expr, 1); add_assoc_stringl_ex(argument_expr, SS("type"), SL("all"), 1); } else { PHALCON_INIT_NVAR(argument_expr); PHALCON_CALL_METHOD_PARAMS_1(argument_expr, this_ptr, "_getexpression", argument); } RETURN_CCTOR(argument_expr); } /** * Resolves a expression in a single call argument * * @param array $expr * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getFunctionCall){ zval *expr, *name, *arguments, *function_args = NULL, *argument = NULL; zval *argument_expr = NULL, *function_call = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &expr) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, expr, SL("name"), PH_NOISY_CC); if (phalcon_array_isset_string(expr, SS("arguments"))) { PHALCON_OBS_VAR(arguments); phalcon_array_fetch_string(&arguments, expr, SL("arguments"), PH_NOISY_CC); if (phalcon_array_isset_long(arguments, 0)) { /** * There are more than one argument */ PHALCON_INIT_VAR(function_args); array_init(function_args); if (!phalcon_is_iterable(arguments, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(argument); PHALCON_INIT_NVAR(argument_expr); PHALCON_CALL_METHOD_PARAMS_1(argument_expr, this_ptr, "_getcallargument", argument); phalcon_array_append(&function_args, argument_expr, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } } else { /** * There is only one argument */ PHALCON_INIT_NVAR(argument_expr); PHALCON_CALL_METHOD_PARAMS_1(argument_expr, this_ptr, "_getcallargument", arguments); PHALCON_INIT_NVAR(function_args); array_init_size(function_args, 1); phalcon_array_append(&function_args, argument_expr, PH_SEPARATE TSRMLS_CC); } PHALCON_INIT_VAR(function_call); array_init_size(function_call, 3); add_assoc_stringl_ex(function_call, SS("type"), SL("functionCall"), 1); phalcon_array_update_string(&function_call, SL("name"), &name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&function_call, SL("arguments"), &function_args, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { PHALCON_INIT_NVAR(function_call); array_init_size(function_call, 2); add_assoc_stringl_ex(function_call, SS("type"), SL("functionCall"), 1); phalcon_array_update_string(&function_call, SL("name"), &name, PH_COPY | PH_SEPARATE TSRMLS_CC); } RETURN_CTOR(function_call); } /** * Resolves an expression from its intermediate code into a string * * @param array $expr * @param boolean $quoting * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getExpression){ zval *expr, *quoting = NULL, *temp_not_quoting, *expr_left; zval *left, *expr_right, *right, *expr_type, *expr_return = NULL; zval *expr_value = NULL, *value = NULL, *escaped_value, *question_mark; zval *double_colon, *placeholder = NULL, *expression_message; zval *expression, *expr_domain, *list_items; zval *expr_list_item = NULL, *expr_item = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &expr, &quoting) == FAILURE) { RETURN_MM_NULL(); } if (!quoting) { PHALCON_INIT_VAR(quoting); ZVAL_BOOL(quoting, 1); } if (phalcon_array_isset_string(expr, SS("type"))) { PHALCON_INIT_VAR(temp_not_quoting); ZVAL_BOOL(temp_not_quoting, 1); /** * Resolving left part of the expression if any */ if (phalcon_array_isset_string(expr, SS("left"))) { PHALCON_OBS_VAR(expr_left); phalcon_array_fetch_string(&expr_left, expr, SL("left"), PH_NOISY_CC); PHALCON_INIT_VAR(left); PHALCON_CALL_METHOD_PARAMS_2(left, this_ptr, "_getexpression", expr_left, temp_not_quoting); } /** * Resolving right part of the expression if any */ if (phalcon_array_isset_string(expr, SS("right"))) { PHALCON_OBS_VAR(expr_right); phalcon_array_fetch_string(&expr_right, expr, SL("right"), PH_NOISY_CC); PHALCON_INIT_VAR(right); PHALCON_CALL_METHOD_PARAMS_2(right, this_ptr, "_getexpression", expr_right, temp_not_quoting); } /** * Every node in the AST has a unique integer type */ PHALCON_OBS_VAR(expr_type); phalcon_array_fetch_string(&expr_type, expr, SL("type"), PH_NOISY_CC); switch (phalcon_get_intval(expr_type)) { case 60: PHALCON_INIT_VAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("<"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 61: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("="), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 62: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL(">"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 270: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("<>"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 271: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("<="), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 272: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL(">="), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 266: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("AND"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 267: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("OR"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 355: PHALCON_INIT_NVAR(expr_return); PHALCON_CALL_METHOD_PARAMS_1(expr_return, this_ptr, "_getqualified", expr); break; case 43: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("+"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 45: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("-"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 42: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("*"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 47: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("/"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 37: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("%"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 38: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("&"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 124: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("|"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 356: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("parentheses"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 367: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 3); add_assoc_stringl_ex(expr_return, SS("type"), SL("unary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("-"), 1); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 258: PHALCON_OBS_VAR(expr_value); phalcon_array_fetch_string(&expr_value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("literal"), 1); phalcon_array_update_string(&expr_return, SL("value"), &expr_value, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 259: PHALCON_OBS_NVAR(expr_value); phalcon_array_fetch_string(&expr_value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("literal"), 1); phalcon_array_update_string(&expr_return, SL("value"), &expr_value, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 260: PHALCON_OBS_VAR(value); phalcon_array_fetch_string(&value, expr, SL("value"), PH_NOISY_CC); if (PHALCON_IS_TRUE(quoting)) { PHALCON_INIT_VAR(escaped_value); PHALCON_CALL_FUNC_PARAMS_1(escaped_value, "addslashes", value); PHALCON_INIT_NVAR(expr_value); PHALCON_CONCAT_SVS(expr_value, "'", escaped_value, "'"); } else { PHALCON_CPY_WRT(expr_value, value); } PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("literal"), 1); phalcon_array_update_string(&expr_return, SL("value"), &expr_value, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 273: PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_VAR(question_mark); ZVAL_STRING(question_mark, "?", 1); PHALCON_INIT_VAR(double_colon); ZVAL_STRING(double_colon, ":", 1); PHALCON_INIT_VAR(placeholder); phalcon_fast_str_replace(placeholder, question_mark, double_colon, value TSRMLS_CC); PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("placeholder"), 1); phalcon_array_update_string(&expr_return, SL("value"), &placeholder, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 274: PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, expr, SL("value"), PH_NOISY_CC); PHALCON_INIT_NVAR(placeholder); PHALCON_CONCAT_SV(placeholder, ":", value); PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("placeholder"), 1); phalcon_array_update_string(&expr_return, SL("value"), &placeholder, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 322: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("literal"), 1); add_assoc_stringl_ex(expr_return, SS("value"), SL("NULL"), 1); break; case 268: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("LIKE"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 351: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("NOT LIKE"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 33: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 3); add_assoc_stringl_ex(expr_return, SS("type"), SL("unary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("NOT "), 1); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 365: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 3); add_assoc_stringl_ex(expr_return, SS("type"), SL("unary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL(" IS NULL"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 366: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 3); add_assoc_stringl_ex(expr_return, SS("type"), SL("unary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL(" IS NOT NULL"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 315: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("IN"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 323: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("NOT IN"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 330: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 3); add_assoc_stringl_ex(expr_return, SS("type"), SL("unary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("DISTINCT "), 1); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 331: PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 4); add_assoc_stringl_ex(expr_return, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(expr_return, SS("op"), SL("BETWEEN"), 1); phalcon_array_update_string(&expr_return, SL("left"), &left, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&expr_return, SL("right"), &right, PH_COPY | PH_SEPARATE TSRMLS_CC); break; case 350: PHALCON_INIT_NVAR(expr_return); PHALCON_CALL_METHOD_PARAMS_1(expr_return, this_ptr, "_getfunctioncall", expr); break; default: PHALCON_INIT_VAR(expression_message); PHALCON_CONCAT_SV(expression_message, "Unknown expression type ", expr_type); PHALCON_INIT_VAR(expression); object_init_ex(expression, phalcon_mvc_model_exception_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(expression, "__construct", expression_message); phalcon_throw_exception(expression TSRMLS_CC); return; } RETURN_CCTOR(expr_return); } /** * Is a qualified column */ if (phalcon_array_isset_string(expr, SS("domain"))) { PHALCON_INIT_VAR(expr_domain); PHALCON_CALL_METHOD_PARAMS_1(expr_domain, this_ptr, "_getqualified", expr); RETURN_CCTOR(expr_domain); } /** * Is the expression doesn't have a type it's a list of nodes */ if (phalcon_array_isset_long(expr, 0)) { PHALCON_INIT_VAR(list_items); array_init(list_items); if (!phalcon_is_iterable(expr, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(expr_list_item); PHALCON_INIT_NVAR(expr_item); PHALCON_CALL_METHOD_PARAMS_1(expr_item, this_ptr, "_getexpression", expr_list_item); phalcon_array_append(&list_items, expr_item, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_NVAR(expr_return); array_init_size(expr_return, 2); add_assoc_stringl_ex(expr_return, SS("type"), SL("list"), 1); phalcon_array_append(&expr_return, list_items, PH_SEPARATE TSRMLS_CC); RETURN_CCTOR(expr_return); } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Unknown expression"); return; } /** * Resolves a column from its intermediate representation into an array used to determine * if the resulset produced is simple or complex * * @param array $column * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getSelectColumn){ zval *column, *sql_columns, *column_type, *models; zval *source = NULL, *model_name = NULL, *sql_column = NULL, *sql_aliases; zval *column_domain, *exception_message = NULL, *sql_column_alias = NULL; zval *sql_aliases_models, *sql_models_aliases; zval *best_alias, *prepared_alias = NULL, *column_data; zval *sql_expr_column, *balias, *sql_alias; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &column) == FAILURE) { RETURN_MM_NULL(); } if (!phalcon_array_isset_string(column, SS("type"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } PHALCON_INIT_VAR(sql_columns); array_init(sql_columns); /** * Check for select * (all) */ PHALCON_OBS_VAR(column_type); phalcon_array_fetch_string(&column_type, column, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(column_type, 352)) { PHALCON_OBS_VAR(models); phalcon_read_property(&models, this_ptr, SL("_models"), PH_NOISY_CC); if (!phalcon_is_iterable(models, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(model_name, ah0, hp0); PHALCON_GET_FOREACH_VALUE(source); PHALCON_INIT_NVAR(sql_column); array_init_size(sql_column, 3); add_assoc_stringl_ex(sql_column, SS("type"), SL("object"), 1); phalcon_array_update_string(&sql_column, SL("model"), &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_column, SL("column"), &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_columns, sql_column, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(sql_columns); } if (!phalcon_array_isset_string(column, SS("column"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } /** * Check if selected column is qualified.* */ if (PHALCON_IS_LONG(column_type, 353)) { PHALCON_OBS_VAR(sql_aliases); phalcon_read_property(&sql_aliases, this_ptr, SL("_sqlAliases"), PH_NOISY_CC); /** * We only allow the alias.* */ PHALCON_OBS_VAR(column_domain); phalcon_array_fetch_string(&column_domain, column, SL("column"), PH_NOISY_CC); if (!phalcon_array_isset(sql_aliases, column_domain)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Unknown table or alias '", column_domain, "' (2)"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Get the SQL alias if any */ PHALCON_OBS_VAR(source); phalcon_array_fetch(&source, sql_aliases, column_domain, PH_NOISY_CC); PHALCON_CPY_WRT(sql_column_alias, source); /** * Get the real source name */ PHALCON_OBS_VAR(sql_aliases_models); phalcon_read_property(&sql_aliases_models, this_ptr, SL("_sqlAliasesModels"), PH_NOISY_CC); PHALCON_OBS_VAR(model_name); phalcon_array_fetch(&model_name, sql_aliases_models, column_domain, PH_NOISY_CC); /** * Get the best alias for the column */ PHALCON_OBS_VAR(sql_models_aliases); phalcon_read_property(&sql_models_aliases, this_ptr, SL("_sqlModelsAliases"), PH_NOISY_CC); PHALCON_OBS_VAR(best_alias); phalcon_array_fetch(&best_alias, sql_models_aliases, model_name, PH_NOISY_CC); /** * If the best alias is the model name we lowercase the first letter */ if (PHALCON_IS_EQUAL(best_alias, model_name)) { PHALCON_INIT_VAR(prepared_alias); PHALCON_CALL_FUNC_PARAMS_1(prepared_alias, "lcfirst", model_name); } else { PHALCON_CPY_WRT(prepared_alias, best_alias); } /** * The sql_column is a complex type returning a complete object */ PHALCON_INIT_NVAR(sql_column); array_init_size(sql_column, 4); add_assoc_stringl_ex(sql_column, SS("type"), SL("object"), 1); phalcon_array_update_string(&sql_column, SL("model"), &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_column, SL("column"), &sql_column_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_column, SL("balias"), &prepared_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_columns, sql_column, PH_SEPARATE TSRMLS_CC); RETURN_CTOR(sql_columns); } /** * Check for columns qualified and not qualified */ if (PHALCON_IS_LONG(column_type, 354)) { /** * The sql_column is a scalar type returning a simple string */ PHALCON_INIT_NVAR(sql_column); array_init_size(sql_column, 1); add_assoc_stringl_ex(sql_column, SS("type"), SL("scalar"), 1); PHALCON_OBS_VAR(column_data); phalcon_array_fetch_string(&column_data, column, SL("column"), PH_NOISY_CC); PHALCON_INIT_VAR(sql_expr_column); PHALCON_CALL_METHOD_PARAMS_1(sql_expr_column, this_ptr, "_getexpression", column_data); /** * Create balias and sqlAlias */ if (phalcon_array_isset_string(sql_expr_column, SS("balias"))) { PHALCON_OBS_VAR(balias); phalcon_array_fetch_string(&balias, sql_expr_column, SL("balias"), PH_NOISY_CC); phalcon_array_update_string(&sql_column, SL("balias"), &balias, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(sql_alias); phalcon_fast_strtolower(sql_alias, balias); phalcon_array_update_string(&sql_column, SL("sqlAlias"), &sql_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_update_string(&sql_column, SL("column"), &sql_expr_column, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_columns, sql_column, PH_SEPARATE TSRMLS_CC); RETURN_CTOR(sql_columns); } PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Unknown type of column ", column_type); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Resolves a table in a SELECT statement checking if the model exists * * @param Phalcon\Mvc\Model\ManagerInterface $manager * @param array $qualifiedName * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getTable){ zval *manager, *qualified_name, *model_name; zval *model, *source, *schema, *complete_source; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &manager, &qualified_name) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_array_isset_string(qualified_name, SS("name"))) { PHALCON_OBS_VAR(model_name); phalcon_array_fetch_string(&model_name, qualified_name, SL("name"), PH_NOISY_CC); PHALCON_INIT_VAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); if (zend_is_true(schema)) { PHALCON_INIT_VAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, schema, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); RETURN_CTOR(complete_source); } RETURN_CCTOR(source); } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } /** * Resolves a JOIN clause checking if the associated models exist * * @param Phalcon\Mvc\Model\ManagerInterface $manager * @param array $join * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getJoin){ zval *manager, *join, *qualified, *qualified_type; zval *model_name, *model, *source, *schema, *data; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &manager, &join) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_array_isset_string(join, SS("qualified"))) { PHALCON_OBS_VAR(qualified); phalcon_array_fetch_string(&qualified, join, SL("qualified"), PH_NOISY_CC); PHALCON_OBS_VAR(qualified_type); phalcon_array_fetch_string(&qualified_type, qualified, SL("type"), PH_NOISY_CC); if (PHALCON_IS_LONG(qualified_type, 355)) { PHALCON_OBS_VAR(model_name); phalcon_array_fetch_string(&model_name, qualified, SL("name"), PH_NOISY_CC); PHALCON_INIT_VAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); PHALCON_INIT_VAR(data); array_init_size(data, 4); phalcon_array_update_string(&data, SL("schema"), &schema, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("source"), &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("modelName"), &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("model"), &model, PH_COPY | PH_SEPARATE TSRMLS_CC); RETURN_CTOR(data); } } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } /** * Resolves a JOIN type * * @param array $join * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getJoinType){ zval *join, *type, *join_type = NULL, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &join) == FAILURE) { RETURN_MM_NULL(); } if (!phalcon_array_isset_string(join, SS("type"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } PHALCON_OBS_VAR(type); phalcon_array_fetch_string(&type, join, SL("type"), PH_NOISY_CC); switch (phalcon_get_intval(type)) { case 360: PHALCON_INIT_VAR(join_type); ZVAL_STRING(join_type, "INNER", 1); break; case 361: PHALCON_INIT_NVAR(join_type); ZVAL_STRING(join_type, "LEFT", 1); break; case 362: PHALCON_INIT_NVAR(join_type); ZVAL_STRING(join_type, "RIGHT", 1); break; case 363: PHALCON_INIT_NVAR(join_type); ZVAL_STRING(join_type, "CROSS", 1); break; case 364: PHALCON_INIT_NVAR(join_type); ZVAL_STRING(join_type, "FULL OUTER", 1); break; default: PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Unknown join type ", type); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } RETURN_CTOR(join_type); } /** * Resolves all the JOINS in a SELECT statement * * @param array $select * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getJoins){ zval *select, *models, *sql_aliases, *sql_aliases_models; zval *sql_models_aliases, *sql_aliases_models_instances; zval *models_instances, *from_models = NULL, *sql_joins; zval *join_models, *join_sources, *join_types; zval *join_pre_condition, *join_prepared; zval *manager = NULL, *joins, *select_joins = NULL, *join_item = NULL; zval *join_data = NULL, *source = NULL, *schema = NULL, *model = NULL, *model_name = NULL; zval *complete_source = NULL, *join_type = NULL, *alias_expr = NULL; zval *alias = NULL, *join_expr = NULL, *pre_condition = NULL, *join_alias = NULL; zval *join_model = NULL, *sql_join_conditions = NULL, *relation = NULL; zval *relations = NULL, *number_relations = NULL, *exception_message = NULL; zval *fields = NULL, *referenced_fields = NULL, *model_alias = NULL; zval *left = NULL, *left_expr = NULL, *right = NULL, *right_expr = NULL, *sql_join_condition = NULL; zval *join_source = NULL, *sql_join = NULL; HashTable *ah0, *ah1, *ah2, *ah3; HashPosition hp0, hp1, hp2, hp3; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &select) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models); phalcon_read_property(&models, this_ptr, SL("_models"), PH_NOISY_CC); PHALCON_OBS_VAR(sql_aliases); phalcon_read_property(&sql_aliases, this_ptr, SL("_sqlAliases"), PH_NOISY_CC); PHALCON_OBS_VAR(sql_aliases_models); phalcon_read_property(&sql_aliases_models, this_ptr, SL("_sqlAliasesModels"), PH_NOISY_CC); PHALCON_OBS_VAR(sql_models_aliases); phalcon_read_property(&sql_models_aliases, this_ptr, SL("_sqlModelsAliases"), PH_NOISY_CC); PHALCON_OBS_VAR(sql_aliases_models_instances); phalcon_read_property(&sql_aliases_models_instances, this_ptr, SL("_sqlAliasesModelsInstances"), PH_NOISY_CC); PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); PHALCON_CPY_WRT(from_models, models); PHALCON_INIT_VAR(sql_joins); array_init(sql_joins); PHALCON_INIT_VAR(join_models); array_init(join_models); PHALCON_INIT_VAR(join_sources); array_init(join_sources); PHALCON_INIT_VAR(join_types); array_init(join_types); PHALCON_INIT_VAR(join_pre_condition); array_init(join_pre_condition); PHALCON_INIT_VAR(join_prepared); array_init(join_prepared); PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_OBS_VAR(joins); phalcon_array_fetch_string(&joins, select, SL("joins"), PH_NOISY_CC); if (!phalcon_array_isset_long(joins, 0)) { PHALCON_INIT_VAR(select_joins); array_init_size(select_joins, 1); phalcon_array_append(&select_joins, joins, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(select_joins, joins); } if (!phalcon_is_iterable(select_joins, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(join_item); PHALCON_INIT_NVAR(join_data); PHALCON_CALL_METHOD_PARAMS_2(join_data, this_ptr, "_getjoin", manager, join_item); PHALCON_OBS_NVAR(source); phalcon_array_fetch_string(&source, join_data, SL("source"), PH_NOISY_CC); PHALCON_OBS_NVAR(schema); phalcon_array_fetch_string(&schema, join_data, SL("schema"), PH_NOISY_CC); PHALCON_OBS_NVAR(model); phalcon_array_fetch_string(&model, join_data, SL("model"), PH_NOISY_CC); PHALCON_OBS_NVAR(model_name); phalcon_array_fetch_string(&model_name, join_data, SL("modelName"), PH_NOISY_CC); PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, schema, PH_SEPARATE TSRMLS_CC); /** * Check join alias */ PHALCON_INIT_NVAR(join_type); PHALCON_CALL_METHOD_PARAMS_1(join_type, this_ptr, "_getjointype", join_item); phalcon_array_update_zval(&join_types, model_name, &join_type, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Process join alias */ if (phalcon_array_isset_string(join_item, SS("alias"))) { PHALCON_OBS_NVAR(alias_expr); phalcon_array_fetch_string(&alias_expr, join_item, SL("alias"), PH_NOISY_CC); PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, alias_expr, SL("name"), PH_NOISY_CC); phalcon_array_append(&complete_source, alias, PH_SEPARATE TSRMLS_CC); /** * Update alias => alias */ phalcon_array_update_zval(&sql_aliases, alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => alias */ phalcon_array_update_zval(&join_models, model_name, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => alias */ phalcon_array_update_zval(&sql_models_aliases, model_name, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => model */ phalcon_array_update_zval(&sql_aliases_models, alias, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update alias => model */ phalcon_array_update_zval(&sql_aliases_models_instances, alias, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => alias */ phalcon_array_update_zval(&models, model_name, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { /** * Update model => source */ phalcon_array_update_zval(&sql_aliases, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => source */ phalcon_array_update_zval(&join_models, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => model */ phalcon_array_update_zval(&sql_models_aliases, model_name, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => model */ phalcon_array_update_zval(&sql_aliases_models, model_name, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => model instance */ phalcon_array_update_zval(&sql_aliases_models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Update model => source */ phalcon_array_update_zval(&models, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&join_sources, model_name, &complete_source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&join_prepared, model_name, &join_item, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * Update temporary properties */ phalcon_update_property_zval(this_ptr, SL("_models"), models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliases"), sql_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModels"), sql_aliases_models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlModelsAliases"), sql_models_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModelsInstances"), sql_aliases_models_instances TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_modelsInstances"), models_instances TSRMLS_CC); if (!phalcon_is_iterable(join_prepared, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_KEY(model_name, ah1, hp1); PHALCON_GET_FOREACH_VALUE(join_item); /** * Check for predefined conditions */ if (phalcon_array_isset_string(join_item, SS("conditions"))) { PHALCON_OBS_NVAR(join_expr); phalcon_array_fetch_string(&join_expr, join_item, SL("conditions"), PH_NOISY_CC); PHALCON_INIT_NVAR(pre_condition); PHALCON_CALL_METHOD_PARAMS_1(pre_condition, this_ptr, "_getexpression", join_expr); phalcon_array_update_zval(&join_pre_condition, model_name, &pre_condition, PH_COPY | PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah1, &hp1); } /** * Create join relationships dynamically */ PHALCON_OBS_NVAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); if (!phalcon_is_iterable(from_models, &ah2, &hp2, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah2, (void**) &hd, &hp2) == SUCCESS) { PHALCON_GET_FOREACH_KEY(model_name, ah2, hp2); PHALCON_GET_FOREACH_VALUE(source); if (!phalcon_is_iterable(join_models, &ah3, &hp3, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah3, (void**) &hd, &hp3) == SUCCESS) { PHALCON_GET_FOREACH_KEY(join_model, ah3, hp3); PHALCON_GET_FOREACH_VALUE(join_alias); PHALCON_INIT_NVAR(sql_join_conditions); array_init(sql_join_conditions); if (!phalcon_array_isset(join_pre_condition, join_model)) { /** * Check if the joined model is an alias */ PHALCON_INIT_NVAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", model_name, join_model); if (PHALCON_IS_FALSE(relation)) { /** * Check for relations between models */ PHALCON_INIT_NVAR(relations); PHALCON_CALL_METHOD_PARAMS_2(relations, manager, "getrelationsbetween", model_name, join_model); if (Z_TYPE_P(relations) == IS_ARRAY) { /** * More than one relation must throw an exception */ PHALCON_INIT_NVAR(number_relations); phalcon_fast_count(number_relations, relations TSRMLS_CC); if (!PHALCON_IS_LONG(number_relations, 1)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "There is more than one relation between '", model_name, "' and '", join_model, "\", the join must be done using an alias"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Get the first relationship */ PHALCON_OBS_NVAR(relation); phalcon_array_fetch_long(&relation, relations, 0, PH_NOISY_CC); } } /** * Valid relations are objects */ if (Z_TYPE_P(relation) == IS_OBJECT) { /** * TODO. Create joins with compound keys */ PHALCON_INIT_NVAR(fields); PHALCON_CALL_METHOD(fields, relation, "getfields"); if (Z_TYPE_P(fields) == IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Not implemented yet"); return; } PHALCON_INIT_NVAR(referenced_fields); PHALCON_CALL_METHOD(referenced_fields, relation, "getreferencedfields"); /** * Get the related model alias of the left part */ PHALCON_OBS_NVAR(model_alias); phalcon_array_fetch(&model_alias, sql_models_aliases, model_name, PH_NOISY_CC); /** * Create the left part of the expression */ PHALCON_INIT_NVAR(left); array_init_size(left, 3); add_assoc_long_ex(left, SS("type"), 355); phalcon_array_update_string(&left, SL("domain"), &model_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&left, SL("name"), &fields, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(left_expr); PHALCON_CALL_METHOD_PARAMS_1(left_expr, this_ptr, "_getqualified", left); /** * Get the related model alias of the right part */ PHALCON_OBS_NVAR(join_alias); phalcon_array_fetch(&join_alias, sql_models_aliases, join_model, PH_NOISY_CC); /** * Create the right part of the expression */ PHALCON_INIT_NVAR(right); array_init_size(right, 3); add_assoc_stringl_ex(right, SS("type"), SL("qualified"), 1); phalcon_array_update_string(&right, SL("domain"), &join_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&right, SL("name"), &referenced_fields, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(right_expr); PHALCON_CALL_METHOD_PARAMS_1(right_expr, this_ptr, "_getqualified", right); /** * Create a binary operation for the join conditions */ PHALCON_INIT_NVAR(sql_join_condition); array_init_size(sql_join_condition, 4); add_assoc_stringl_ex(sql_join_condition, SS("type"), SL("binary-op"), 1); add_assoc_stringl_ex(sql_join_condition, SS("op"), SL("="), 1); phalcon_array_update_string(&sql_join_condition, SL("left"), &left_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_join_condition, SL("right"), &right_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_join_conditions, sql_join_condition, PH_SEPARATE TSRMLS_CC); } } else { PHALCON_OBS_NVAR(pre_condition); phalcon_array_fetch(&pre_condition, join_pre_condition, join_model, PH_NOISY_CC); phalcon_array_append(&sql_join_conditions, pre_condition, PH_SEPARATE TSRMLS_CC); } PHALCON_OBS_NVAR(join_type); phalcon_array_fetch(&join_type, join_types, join_model, PH_NOISY_CC); PHALCON_OBS_NVAR(join_source); phalcon_array_fetch(&join_source, join_sources, join_model, PH_NOISY_CC); /** * Final join representation */ PHALCON_INIT_NVAR(sql_join); array_init_size(sql_join, 3); phalcon_array_update_string(&sql_join, SL("type"), &join_type, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_join, SL("source"), &join_source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_join, SL("conditions"), &sql_join_conditions, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_joins, sql_join, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah3, &hp3); } zend_hash_move_forward_ex(ah2, &hp2); } RETURN_CTOR(sql_joins); } /** * Returns a processed order clause for a SELECT statement * * @param array $order * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getOrderClause){ zval *order, *order_columns = NULL, *order_parts, *order_item = NULL; zval *order_column = NULL, *order_part_expr = NULL, *order_sort = NULL; zval *order_part_sort = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &order) == FAILURE) { RETURN_MM_NULL(); } if (!phalcon_array_isset_long(order, 0)) { PHALCON_INIT_VAR(order_columns); array_init_size(order_columns, 1); phalcon_array_append(&order_columns, order, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(order_columns, order); } PHALCON_INIT_VAR(order_parts); array_init(order_parts); if (!phalcon_is_iterable(order_columns, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(order_item); PHALCON_OBS_NVAR(order_column); phalcon_array_fetch_string(&order_column, order_item, SL("column"), PH_NOISY_CC); PHALCON_INIT_NVAR(order_part_expr); PHALCON_CALL_METHOD_PARAMS_1(order_part_expr, this_ptr, "_getexpression", order_column); /** * Check if the order has a predefined ordering mode */ if (phalcon_array_isset_string(order_item, SS("sort"))) { PHALCON_OBS_NVAR(order_sort); phalcon_array_fetch_string(&order_sort, order_item, SL("sort"), PH_NOISY_CC); if (PHALCON_IS_LONG(order_sort, 327)) { PHALCON_INIT_NVAR(order_part_sort); array_init_size(order_part_sort, 2); phalcon_array_append(&order_part_sort, order_part_expr, PH_SEPARATE TSRMLS_CC); add_next_index_stringl(order_part_sort, SL("ASC"), 1); } else { PHALCON_INIT_NVAR(order_part_sort); array_init_size(order_part_sort, 2); phalcon_array_append(&order_part_sort, order_part_expr, PH_SEPARATE TSRMLS_CC); add_next_index_stringl(order_part_sort, SL("DESC"), 1); } } else { PHALCON_INIT_NVAR(order_part_sort); array_init_size(order_part_sort, 1); phalcon_array_append(&order_part_sort, order_part_expr, PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&order_parts, order_part_sort, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(order_parts); } /** * Returns a processed group clause for a SELECT statement * * @param array $group * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getGroupClause){ zval *group, *group_parts = NULL, *group_item = NULL, *group_part_expr = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &group) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_array_isset_long(group, 0)) { /** * The select is gruped by several columns */ PHALCON_INIT_VAR(group_parts); array_init(group_parts); if (!phalcon_is_iterable(group, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(group_item); PHALCON_INIT_NVAR(group_part_expr); PHALCON_CALL_METHOD_PARAMS_1(group_part_expr, this_ptr, "_getexpression", group_item); phalcon_array_append(&group_parts, group_part_expr, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } } else { PHALCON_INIT_NVAR(group_part_expr); PHALCON_CALL_METHOD_PARAMS_1(group_part_expr, this_ptr, "_getexpression", group); PHALCON_INIT_NVAR(group_parts); array_init_size(group_parts, 1); phalcon_array_append(&group_parts, group_part_expr, PH_SEPARATE TSRMLS_CC); } RETURN_CTOR(group_parts); } /** * Analyzes a SELECT intermediate code and produces an array to be executed later * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _prepareSelect){ zval *ast, *select, *sql_models, *sql_tables, *sql_aliases; zval *sql_columns, *sql_aliases_models, *sql_models_aliases; zval *sql_aliases_models_instances, *models; zval *models_instances, *tables, *selected_models = NULL; zval *manager, *meta_data, *selected_model = NULL, *qualified_name = NULL; zval *model_name = NULL, *model = NULL, *schema = NULL, *source = NULL, *complete_source = NULL; zval *alias = NULL, *exception_message = NULL, *sql_joins = NULL; zval *columns, *select_columns = NULL, *position, *sql_column_aliases; zval *column = NULL, *sql_column_group = NULL, *sql_column = NULL; zval *lower_alias = NULL, *type = NULL, *sql_select, *where, *where_expr; zval *group_by, *sql_group, *having, *having_expr; zval *order, *sql_order, *limit; zval *r0 = NULL; HashTable *ah0, *ah1, *ah2; HashPosition hp0, hp1, hp2; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(ast); phalcon_read_property(&ast, this_ptr, SL("_ast"), PH_NOISY_CC); PHALCON_OBS_VAR(select); phalcon_array_fetch_string(&select, ast, SL("select"), PH_NOISY_CC); if (!phalcon_array_isset_string(select, SS("tables"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } if (!phalcon_array_isset_string(select, SS("columns"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted SELECT AST"); return; } /** * sql_models are all the models that are using in the query */ PHALCON_INIT_VAR(sql_models); array_init(sql_models); /** * sql_tables are all the mapped sources regarding the models in use */ PHALCON_INIT_VAR(sql_tables); array_init(sql_tables); /** * sql_aliases are the aliases as keys and the mapped sources as values */ PHALCON_INIT_VAR(sql_aliases); array_init(sql_aliases); /** * sql_columns are all every column expression */ PHALCON_INIT_VAR(sql_columns); array_init(sql_columns); /** * sql_aliases_models are the aliases as keys and the model names as values */ PHALCON_INIT_VAR(sql_aliases_models); array_init(sql_aliases_models); /** * sql_aliases_models are the model names as keys and the aliases as values */ PHALCON_INIT_VAR(sql_models_aliases); array_init(sql_models_aliases); /** * sql_aliases_models_instances are the aliases as keys and the model instances as * values */ PHALCON_INIT_VAR(sql_aliases_models_instances); array_init(sql_aliases_models_instances); /** * Models information */ PHALCON_INIT_VAR(models); array_init(models); PHALCON_INIT_VAR(models_instances); array_init(models_instances); PHALCON_OBS_VAR(tables); phalcon_array_fetch_string(&tables, select, SL("tables"), PH_NOISY_CC); if (!phalcon_array_isset_long(tables, 0)) { PHALCON_INIT_VAR(selected_models); array_init_size(selected_models, 1); phalcon_array_append(&selected_models, tables, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(selected_models, tables); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC); /** * Processing selected columns */ if (!phalcon_is_iterable(selected_models, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(selected_model); PHALCON_OBS_NVAR(qualified_name); phalcon_array_fetch_string(&qualified_name, selected_model, SL("qualifiedName"), PH_NOISY_CC); PHALCON_OBS_NVAR(model_name); phalcon_array_fetch_string(&model_name, qualified_name, SL("name"), PH_NOISY_CC); PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); /** * Define a complete schema/source */ PHALCON_INIT_NVAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); PHALCON_INIT_NVAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); if (zend_is_true(schema)) { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, schema, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(complete_source, source); } /** * If an alias is defined for a model the model cannot be referenced in the column * list */ if (phalcon_array_isset_string(selected_model, SS("alias"))) { PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, selected_model, SL("alias"), PH_NOISY_CC); if (phalcon_array_isset(sql_aliases, alias)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Alias \"", alias, " is already used"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_array_update_zval(&sql_aliases, alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models, alias, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_models_aliases, model_name, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, alias, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Append or convert complete source to an array */ if (Z_TYPE_P(complete_source) == IS_ARRAY) { phalcon_array_append(&complete_source, alias, PH_SEPARATE TSRMLS_CC); } else { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 3); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); add_next_index_null(complete_source); phalcon_array_append(&complete_source, alias, PH_SEPARATE TSRMLS_CC); } phalcon_array_update_zval(&models, model_name, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&sql_aliases, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models, model_name, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_models_aliases, model_name, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&sql_models, model_name, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_tables, complete_source, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * Assign Models/Tables information */ phalcon_update_property_zval(this_ptr, SL("_models"), models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_modelsInstances"), models_instances TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliases"), sql_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModels"), sql_aliases_models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlModelsAliases"), sql_models_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModelsInstances"), sql_aliases_models_instances TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_modelsInstances"), models_instances TSRMLS_CC); /** * Processing joins */ if (phalcon_array_isset_string(select, SS("joins"))) { PHALCON_OBS_VAR(r0); phalcon_array_fetch_string(&r0, select, SL("joins"), PH_NOISY_CC); if (phalcon_fast_count_ev(r0 TSRMLS_CC)) { PHALCON_INIT_VAR(sql_joins); PHALCON_CALL_METHOD_PARAMS_1(sql_joins, this_ptr, "_getjoins", select); } else { PHALCON_INIT_NVAR(sql_joins); array_init(sql_joins); } } else { PHALCON_INIT_NVAR(sql_joins); array_init(sql_joins); } /** * Processing selected columns */ PHALCON_OBS_VAR(columns); phalcon_array_fetch_string(&columns, select, SL("columns"), PH_NOISY_CC); if (!phalcon_array_isset_long(columns, 0)) { PHALCON_INIT_VAR(select_columns); array_init_size(select_columns, 1); phalcon_array_append(&select_columns, columns, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(select_columns, columns); } /** * Resolve selected columns */ PHALCON_INIT_VAR(position); ZVAL_LONG(position, 0); PHALCON_INIT_VAR(sql_column_aliases); array_init(sql_column_aliases); if (!phalcon_is_iterable(select_columns, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(column); PHALCON_INIT_NVAR(sql_column_group); PHALCON_CALL_METHOD_PARAMS_1(sql_column_group, this_ptr, "_getselectcolumn", column); if (!phalcon_is_iterable(sql_column_group, &ah2, &hp2, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah2, (void**) &hd, &hp2) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(sql_column); /** * If 'alias' is set, the user had defined a alias for the column */ if (phalcon_array_isset_string(column, SS("alias"))) { PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, column, SL("alias"), PH_NOISY_CC); /** * The best alias is the one provided by the user */ phalcon_array_update_string(&sql_column, SL("balias"), &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Calculate a lowercased version of the alias */ PHALCON_INIT_NVAR(lower_alias); phalcon_fast_strtolower(lower_alias, alias); phalcon_array_update_string(&sql_column, SL("sqlAlias"), &lower_alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_columns, alias, &sql_column, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval_bool(&sql_column_aliases, alias, 1, PH_SEPARATE TSRMLS_CC); } else { /** * 'balias' is the best alias selected for the column */ if (phalcon_array_isset_string(sql_column, SS("balias"))) { PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, sql_column, SL("balias"), PH_NOISY_CC); phalcon_array_update_zval(&sql_columns, alias, &sql_column, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, sql_column, SL("type"), PH_NOISY_CC); if (PHALCON_IS_STRING(type, "scalar")) { PHALCON_INIT_NVAR(alias); PHALCON_CONCAT_SV(alias, "_", position); phalcon_array_update_zval(&sql_columns, alias, &sql_column, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&sql_columns, sql_column, PH_SEPARATE TSRMLS_CC); } } } PHALCON_SEPARATE(position); increment_function(position); zend_hash_move_forward_ex(ah2, &hp2); } zend_hash_move_forward_ex(ah1, &hp1); } phalcon_update_property_zval(this_ptr, SL("_sqlColumnAliases"), sql_column_aliases TSRMLS_CC); /** * sql_select is the final prepared SELECT */ PHALCON_INIT_VAR(sql_select); array_init_size(sql_select, 3); phalcon_array_update_string(&sql_select, SL("models"), &sql_models, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_select, SL("tables"), &sql_tables, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_select, SL("columns"), &sql_columns, PH_COPY | PH_SEPARATE TSRMLS_CC); if (phalcon_fast_count_ev(sql_joins TSRMLS_CC)) { phalcon_array_update_string(&sql_select, SL("joins"), &sql_joins, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Process WHERE clause if any */ if (phalcon_array_isset_string(ast, SS("where"))) { PHALCON_OBS_VAR(where); phalcon_array_fetch_string(&where, ast, SL("where"), PH_NOISY_CC); PHALCON_INIT_VAR(where_expr); PHALCON_CALL_METHOD_PARAMS_1(where_expr, this_ptr, "_getexpression", where); phalcon_array_update_string(&sql_select, SL("where"), &where_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Process GROUP BY clause if any */ if (phalcon_array_isset_string(ast, SS("groupBy"))) { PHALCON_OBS_VAR(group_by); phalcon_array_fetch_string(&group_by, ast, SL("groupBy"), PH_NOISY_CC); PHALCON_INIT_VAR(sql_group); PHALCON_CALL_METHOD_PARAMS_1(sql_group, this_ptr, "_getgroupclause", group_by); phalcon_array_update_string(&sql_select, SL("group"), &sql_group, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Process HAVING clause if any */ if (phalcon_array_isset_string(ast, SS("having"))) { PHALCON_OBS_VAR(having); phalcon_array_fetch_string(&having, ast, SL("having"), PH_NOISY_CC); PHALCON_INIT_VAR(having_expr); PHALCON_CALL_METHOD_PARAMS_1(having_expr, this_ptr, "_getexpression", having); phalcon_array_update_string(&sql_select, SL("having"), &having_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Process ORDER BY clause if any */ if (phalcon_array_isset_string(ast, SS("orderBy"))) { PHALCON_OBS_VAR(order); phalcon_array_fetch_string(&order, ast, SL("orderBy"), PH_NOISY_CC); PHALCON_INIT_VAR(sql_order); PHALCON_CALL_METHOD_PARAMS_1(sql_order, this_ptr, "_getorderclause", order); phalcon_array_update_string(&sql_select, SL("order"), &sql_order, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Process LIMIT clause if any */ if (phalcon_array_isset_string(ast, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, ast, SL("limit"), PH_NOISY_CC); phalcon_array_update_string(&sql_select, SL("limit"), &limit, PH_COPY | PH_SEPARATE TSRMLS_CC); } RETURN_CTOR(sql_select); } /** * Analyzes an INSERT intermediate code and produces an array to be executed later * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _prepareInsert){ zval *ast, *qualified_name, *manager, *model_name; zval *model, *source = NULL, *schema, *sql_aliases, *not_quoting; zval *expr_values, *values, *expr_value = NULL, *expr_insert = NULL; zval *expr_type = NULL, *value = NULL, *sql_insert, *meta_data; zval *sql_fields, *fields, *field = NULL, *name = NULL, *has_attribute = NULL; zval *exception_message = NULL; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(ast); phalcon_read_property(&ast, this_ptr, SL("_ast"), PH_NOISY_CC); if (!phalcon_array_isset_string(ast, SS("qualifiedName"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted INSERT AST"); return; } if (!phalcon_array_isset_string(ast, SS("values"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted INSERT AST"); return; } PHALCON_OBS_VAR(qualified_name); phalcon_array_fetch_string(&qualified_name, ast, SL("qualifiedName"), PH_NOISY_CC); /** * Check if the related model exists */ if (!phalcon_array_isset_string(qualified_name, SS("name"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted INSERT AST"); return; } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_OBS_VAR(model_name); phalcon_array_fetch_string(&model_name, qualified_name, SL("name"), PH_NOISY_CC); PHALCON_INIT_VAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); if (zend_is_true(schema)) { PHALCON_INIT_NVAR(source); array_init_size(source, 2); phalcon_array_append(&source, schema, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&source, source, PH_SEPARATE TSRMLS_CC); } PHALCON_INIT_VAR(sql_aliases); array_init(sql_aliases); PHALCON_INIT_VAR(not_quoting); ZVAL_BOOL(not_quoting, 0); PHALCON_INIT_VAR(expr_values); array_init(expr_values); PHALCON_OBS_VAR(values); phalcon_array_fetch_string(&values, ast, SL("values"), PH_NOISY_CC); if (!phalcon_is_iterable(values, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(expr_value); PHALCON_INIT_NVAR(expr_insert); PHALCON_CALL_METHOD_PARAMS_2(expr_insert, this_ptr, "_getexpression", expr_value, not_quoting); PHALCON_OBS_NVAR(expr_type); phalcon_array_fetch_string(&expr_type, expr_value, SL("type"), PH_NOISY_CC); PHALCON_INIT_NVAR(value); array_init_size(value, 2); phalcon_array_update_string(&value, SL("type"), &expr_type, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&value, SL("value"), &expr_insert, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&expr_values, value, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(sql_insert); array_init(sql_insert); phalcon_array_update_string(&sql_insert, SL("model"), &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_insert, SL("table"), &source, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC); if (phalcon_array_isset_string(ast, SS("fields"))) { PHALCON_INIT_VAR(sql_fields); array_init(sql_fields); PHALCON_OBS_VAR(fields); phalcon_array_fetch_string(&fields, ast, SL("fields"), PH_NOISY_CC); if (!phalcon_is_iterable(fields, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); PHALCON_OBS_NVAR(name); phalcon_array_fetch_string(&name, field, SL("name"), PH_NOISY_CC); PHALCON_INIT_NVAR(has_attribute); PHALCON_CALL_METHOD_PARAMS_2(has_attribute, meta_data, "hasattribute", model, name); if (!zend_is_true(has_attribute)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "The model '", model_name, "' doesn't have the attribute '", name, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_array_append(&sql_fields, name, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } phalcon_array_update_string(&sql_insert, SL("fields"), &sql_fields, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_update_string(&sql_insert, SL("values"), &expr_values, PH_COPY | PH_SEPARATE TSRMLS_CC); RETURN_CTOR(sql_insert); } /** * Analyzes an UPDATE intermediate code and produces an array to be executed later * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _prepareUpdate){ zval *ast, *update, *models, *models_instances; zval *sql_tables, *sql_models, *sql_aliases; zval *sql_aliases_models_instances, *tables; zval *update_tables = NULL, *manager, *table = NULL, *qualified_name = NULL; zval *model_name = NULL, *model = NULL, *source = NULL, *schema = NULL, *complete_source = NULL; zval *alias = NULL, *sql_fields, *sql_values, *values; zval *update_values = NULL, *not_quoting = NULL, *update_value = NULL; zval *column = NULL, *sql_column = NULL, *expr_column = NULL, *expr_value = NULL; zval *type = NULL, *value = NULL, *sql_update, *where, *where_expr; zval *limit; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(ast); phalcon_read_property(&ast, this_ptr, SL("_ast"), PH_NOISY_CC); if (!phalcon_array_isset_string(ast, SS("update"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted UPDATE AST"); return; } PHALCON_OBS_VAR(update); phalcon_array_fetch_string(&update, ast, SL("update"), PH_NOISY_CC); if (!phalcon_array_isset_string(update, SS("tables"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted UPDATE AST"); return; } if (!phalcon_array_isset_string(update, SS("values"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted UPDATE AST"); return; } /** * We use these arrays to store info related to models, alias and its sources. With * them we can rename columns later */ PHALCON_INIT_VAR(models); array_init(models); PHALCON_INIT_VAR(models_instances); array_init(models_instances); PHALCON_INIT_VAR(sql_tables); array_init(sql_tables); PHALCON_INIT_VAR(sql_models); array_init(sql_models); PHALCON_INIT_VAR(sql_aliases); array_init(sql_aliases); PHALCON_INIT_VAR(sql_aliases_models_instances); array_init(sql_aliases_models_instances); PHALCON_OBS_VAR(tables); phalcon_array_fetch_string(&tables, update, SL("tables"), PH_NOISY_CC); if (!phalcon_array_isset_long(tables, 0)) { PHALCON_INIT_VAR(update_tables); array_init_size(update_tables, 1); phalcon_array_append(&update_tables, tables, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(update_tables, tables); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); if (!phalcon_is_iterable(update_tables, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(table); PHALCON_OBS_NVAR(qualified_name); phalcon_array_fetch_string(&qualified_name, table, SL("qualifiedName"), PH_NOISY_CC); PHALCON_OBS_NVAR(model_name); phalcon_array_fetch_string(&model_name, qualified_name, SL("name"), PH_NOISY_CC); PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); PHALCON_INIT_NVAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_NVAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); if (zend_is_true(schema)) { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, schema, PH_SEPARATE TSRMLS_CC); } else { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); add_next_index_null(complete_source); } if (phalcon_array_isset_string(table, SS("alias"))) { PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, table, SL("alias"), PH_NOISY_CC); phalcon_array_update_zval(&sql_aliases, alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, alias, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_tables, complete_source, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, alias, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models, alias, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&sql_aliases, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_tables, source, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&sql_models, model_name, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * Update the models/alias/sources in the object */ phalcon_update_property_zval(this_ptr, SL("_models"), models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_modelsInstances"), models_instances TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliases"), sql_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModelsInstances"), sql_aliases_models_instances TSRMLS_CC); PHALCON_INIT_VAR(sql_fields); array_init(sql_fields); PHALCON_INIT_VAR(sql_values); array_init(sql_values); PHALCON_OBS_VAR(values); phalcon_array_fetch_string(&values, update, SL("values"), PH_NOISY_CC); if (!phalcon_array_isset_long(values, 0)) { PHALCON_INIT_VAR(update_values); array_init_size(update_values, 1); phalcon_array_append(&update_values, values, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(update_values, values); } PHALCON_INIT_VAR(not_quoting); ZVAL_BOOL(not_quoting, 0); if (!phalcon_is_iterable(update_values, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(update_value); PHALCON_OBS_NVAR(column); phalcon_array_fetch_string(&column, update_value, SL("column"), PH_NOISY_CC); PHALCON_INIT_NVAR(sql_column); PHALCON_CALL_METHOD_PARAMS_2(sql_column, this_ptr, "_getexpression", column, not_quoting); phalcon_array_append(&sql_fields, sql_column, PH_SEPARATE TSRMLS_CC); PHALCON_OBS_NVAR(expr_column); phalcon_array_fetch_string(&expr_column, update_value, SL("expr"), PH_NOISY_CC); PHALCON_INIT_NVAR(expr_value); PHALCON_CALL_METHOD_PARAMS_2(expr_value, this_ptr, "_getexpression", expr_column, not_quoting); PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, expr_column, SL("type"), PH_NOISY_CC); PHALCON_INIT_NVAR(value); array_init_size(value, 2); phalcon_array_update_string(&value, SL("type"), &type, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&value, SL("value"), &expr_value, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_values, value, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } PHALCON_INIT_VAR(sql_update); array_init(sql_update); phalcon_array_update_string(&sql_update, SL("tables"), &sql_tables, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_update, SL("models"), &sql_models, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_update, SL("fields"), &sql_fields, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_update, SL("values"), &sql_values, PH_COPY | PH_SEPARATE TSRMLS_CC); if (phalcon_array_isset_string(ast, SS("where"))) { ZVAL_BOOL(not_quoting, 1); PHALCON_OBS_VAR(where); phalcon_array_fetch_string(&where, ast, SL("where"), PH_NOISY_CC); PHALCON_INIT_VAR(where_expr); PHALCON_CALL_METHOD_PARAMS_2(where_expr, this_ptr, "_getexpression", where, not_quoting); phalcon_array_update_string(&sql_update, SL("where"), &where_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); } if (phalcon_array_isset_string(ast, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, ast, SL("limit"), PH_NOISY_CC); phalcon_array_update_string(&sql_update, SL("limit"), &limit, PH_COPY | PH_SEPARATE TSRMLS_CC); } RETURN_CTOR(sql_update); } /** * Analyzes a DELETE intermediate code and produces an array to be executed later * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, _prepareDelete){ zval *ast, *delete, *models, *models_instances; zval *sql_tables, *sql_models, *sql_aliases; zval *sql_aliases_models_instances, *tables; zval *delete_tables = NULL, *manager, *table = NULL, *qualified_name = NULL; zval *model_name = NULL, *model = NULL, *source = NULL, *schema = NULL, *complete_source = NULL; zval *alias = NULL, *sql_delete, *not_quoting, *where; zval *where_expr, *limit; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(ast); phalcon_read_property(&ast, this_ptr, SL("_ast"), PH_NOISY_CC); if (!phalcon_array_isset_string(ast, SS("delete"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted DELETE AST"); return; } PHALCON_OBS_VAR(delete); phalcon_array_fetch_string(&delete, ast, SL("delete"), PH_NOISY_CC); if (!phalcon_array_isset_string(delete, SS("tables"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted DELETE AST"); return; } /** * We use these arrays to store info related to models, alias and its sources. With * them we can rename columns later */ PHALCON_INIT_VAR(models); array_init(models); PHALCON_INIT_VAR(models_instances); array_init(models_instances); PHALCON_INIT_VAR(sql_tables); array_init(sql_tables); PHALCON_INIT_VAR(sql_models); array_init(sql_models); PHALCON_INIT_VAR(sql_aliases); array_init(sql_aliases); PHALCON_INIT_VAR(sql_aliases_models_instances); array_init(sql_aliases_models_instances); PHALCON_OBS_VAR(tables); phalcon_array_fetch_string(&tables, delete, SL("tables"), PH_NOISY_CC); if (!phalcon_array_isset_long(tables, 0)) { PHALCON_INIT_VAR(delete_tables); array_init_size(delete_tables, 1); phalcon_array_append(&delete_tables, tables, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(delete_tables, tables); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); if (!phalcon_is_iterable(delete_tables, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(table); PHALCON_OBS_NVAR(qualified_name); phalcon_array_fetch_string(&qualified_name, table, SL("qualifiedName"), PH_NOISY_CC); PHALCON_OBS_NVAR(model_name); phalcon_array_fetch_string(&model_name, qualified_name, SL("name"), PH_NOISY_CC); PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); PHALCON_INIT_NVAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_NVAR(schema); PHALCON_CALL_METHOD(schema, model, "getschema"); if (zend_is_true(schema)) { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, schema, PH_SEPARATE TSRMLS_CC); } else { PHALCON_INIT_NVAR(complete_source); array_init_size(complete_source, 2); phalcon_array_append(&complete_source, source, PH_SEPARATE TSRMLS_CC); add_next_index_null(complete_source); } if (phalcon_array_isset_string(table, SS("alias"))) { PHALCON_OBS_NVAR(alias); phalcon_array_fetch_string(&alias, table, SL("alias"), PH_NOISY_CC); phalcon_array_update_zval(&sql_aliases, alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&complete_source, alias, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_tables, complete_source, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, alias, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models, alias, &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&sql_aliases, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&sql_aliases_models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&sql_tables, source, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models, model_name, &source, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&sql_models, model_name, PH_SEPARATE TSRMLS_CC); phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * Update the models/alias/sources in the object */ phalcon_update_property_zval(this_ptr, SL("_models"), models TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_modelsInstances"), models_instances TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliases"), sql_aliases TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_sqlAliasesModelsInstances"), sql_aliases_models_instances TSRMLS_CC); PHALCON_INIT_VAR(sql_delete); array_init(sql_delete); phalcon_array_update_string(&sql_delete, SL("tables"), &sql_tables, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&sql_delete, SL("models"), &sql_models, PH_COPY | PH_SEPARATE TSRMLS_CC); if (phalcon_array_isset_string(ast, SS("where"))) { PHALCON_INIT_VAR(not_quoting); ZVAL_BOOL(not_quoting, 1); PHALCON_OBS_VAR(where); phalcon_array_fetch_string(&where, ast, SL("where"), PH_NOISY_CC); PHALCON_INIT_VAR(where_expr); PHALCON_CALL_METHOD_PARAMS_2(where_expr, this_ptr, "_getexpression", where, not_quoting); phalcon_array_update_string(&sql_delete, SL("where"), &where_expr, PH_COPY | PH_SEPARATE TSRMLS_CC); } if (phalcon_array_isset_string(ast, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, ast, SL("limit"), PH_NOISY_CC); phalcon_array_update_string(&sql_delete, SL("limit"), &limit, PH_COPY | PH_SEPARATE TSRMLS_CC); } RETURN_CTOR(sql_delete); } /** * Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another * intermediate representation that could be executed by Phalcon\Mvc\Model\Query * * @param Phalcon\Mvc\Model\ManagerInterface $manager * @param Phalcon\Mvc\Model\MetaDataInterface $metaData * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, parse){ zval *intermediate, *phql, *ast, *ir_phql = NULL, *type, *exception_message; PHALCON_MM_GROW(); PHALCON_OBS_VAR(intermediate); phalcon_read_property(&intermediate, this_ptr, SL("_intermediate"), PH_NOISY_CC); if (Z_TYPE_P(intermediate) == IS_ARRAY) { RETURN_CCTOR(intermediate); } PHALCON_OBS_VAR(phql); phalcon_read_property(&phql, this_ptr, SL("_phql"), PH_NOISY_CC); /** * This function parses the PHQL statement */ PHALCON_INIT_VAR(ast); if (phql_parse_phql(ast, phql TSRMLS_CC) == FAILURE) { return; } phalcon_update_property_zval(this_ptr, SL("_ast"), ast TSRMLS_CC); PHALCON_INIT_VAR(ir_phql); if (Z_TYPE_P(ast) == IS_ARRAY) { if (phalcon_array_isset_string(ast, SS("type"))) { /** * Produce an independent database system representation */ PHALCON_OBS_VAR(type); phalcon_array_fetch_string(&type, ast, SL("type"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_type"), type TSRMLS_CC); switch (phalcon_get_intval(type)) { case 309: PHALCON_CALL_METHOD(ir_phql, this_ptr, "_prepareselect"); break; case 306: PHALCON_INIT_NVAR(ir_phql); PHALCON_CALL_METHOD(ir_phql, this_ptr, "_prepareinsert"); break; case 300: PHALCON_INIT_NVAR(ir_phql); PHALCON_CALL_METHOD(ir_phql, this_ptr, "_prepareupdate"); break; case 303: PHALCON_INIT_NVAR(ir_phql); PHALCON_CALL_METHOD(ir_phql, this_ptr, "_preparedelete"); break; default: PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Unknown statement ", type); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } } if (Z_TYPE_P(ir_phql) == IS_NULL) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Corrupted AST"); return; } phalcon_update_property_zval(this_ptr, SL("_intermediate"), ir_phql TSRMLS_CC); RETURN_CCTOR(ir_phql); } /** * Sets the cache parameters of the query * * @param array $cacheOptions * @return Phalcon\Mvc\Model\Query */ PHP_METHOD(Phalcon_Mvc_Model_Query, cache){ zval *cache_options; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &cache_options) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_cacheOptions"), cache_options TSRMLS_CC); RETURN_THISW(); } /** * Returns the current cache options * * @param array */ PHP_METHOD(Phalcon_Mvc_Model_Query, getCacheOptions){ RETURN_MEMBER(this_ptr, "_cacheOptions"); } /** * Returns the current cache backend instance * * @return Phalcon\Cache\BackendInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, getCache){ RETURN_MEMBER(this_ptr, "_cache"); } /** * Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, _executeSelect){ zval *intermediate, *bind_params, *bind_types; zval *manager, *models_instances = NULL, *models, *number_models; zval *model_name = NULL, *model = NULL, *connection = NULL, *connections; zval *type = NULL, *connection_types = NULL, *columns, *have_objects = NULL; zval *have_scalars = NULL, *is_complex = NULL, *number_objects; zval *column = NULL, *column_type = NULL, *is_simple_std = NULL, *select_columns; zval *simple_column_map = NULL, *meta_data, *alias = NULL; zval *sql_column = NULL, *instance = NULL, *attributes = NULL, *column_map = NULL; zval *attribute = NULL, *hidden_alias = NULL, *column_alias = NULL; zval *sql_alias = NULL, *dialect, *sql_select, *processed = NULL; zval *value = NULL, *wildcard = NULL, *string_wildcard = NULL, *processed_types = NULL; zval *result, *count, *result_data = NULL, *cache, *result_object = NULL; zval *resultset = NULL; HashTable *ah0, *ah1, *ah2, *ah3, *ah4, *ah5, *ah6; HashPosition hp0, hp1, hp2, hp3, hp4, hp5, hp6; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &intermediate, &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } PHALCON_SEPARATE_PARAM(intermediate); PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); /** * Models instances is an array if the SELECT was prepared with parse */ PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); if (Z_TYPE_P(models_instances) != IS_ARRAY) { PHALCON_INIT_NVAR(models_instances); array_init(models_instances); } PHALCON_OBS_VAR(models); phalcon_array_fetch_string(&models, intermediate, SL("models"), PH_NOISY_CC); PHALCON_INIT_VAR(number_models); phalcon_fast_count(number_models, models TSRMLS_CC); if (PHALCON_IS_LONG(number_models, 1)) { /** * Load first model if is not loaded */ PHALCON_OBS_VAR(model_name); phalcon_array_fetch_long(&model_name, models, 0, PH_NOISY_CC); if (!phalcon_array_isset(models_instances, model_name)) { PHALCON_INIT_VAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); } else { PHALCON_OBS_NVAR(model); phalcon_array_fetch(&model, models_instances, model_name, PH_NOISY_CC); } /** * Get the current connection to the model */ PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, model, "getconnection"); phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { /** * Check if all the models belongs to the same connection */ PHALCON_INIT_VAR(connections); array_init(connections); if (!phalcon_is_iterable(models, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(model_name); if (!phalcon_array_isset(models_instances, model_name)) { PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); } else { PHALCON_OBS_NVAR(model); phalcon_array_fetch(&model, models_instances, model_name, PH_NOISY_CC); } /** * Get the models connection */ PHALCON_INIT_NVAR(connection); PHALCON_CALL_METHOD(connection, model, "getconnection"); /** * Get the type of connection the model is using (mysql, postgresql, etc) */ PHALCON_INIT_NVAR(type); PHALCON_CALL_METHOD(type, connection, "gettype"); /** * Mark the type of connection in the connection flags */ phalcon_array_update_zval_bool(&connections, type, 1, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(connection_types); phalcon_fast_count(connection_types, connections TSRMLS_CC); /** * More than one type of connection is not allowed */ if (PHALCON_IS_LONG(connection_types, 2)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Cannot use models of different database systems in the same query"); return; } /** * Register the model instance */ phalcon_array_update_zval(&models_instances, model_name, &model, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } } PHALCON_OBS_VAR(columns); phalcon_array_fetch_string(&columns, intermediate, SL("columns"), PH_NOISY_CC); PHALCON_INIT_VAR(have_objects); ZVAL_BOOL(have_objects, 0); PHALCON_INIT_VAR(have_scalars); ZVAL_BOOL(have_scalars, 0); PHALCON_INIT_VAR(is_complex); ZVAL_BOOL(is_complex, 0); /** * Check if the resultset have objects and how many of them have */ PHALCON_INIT_VAR(number_objects); ZVAL_LONG(number_objects, 0); if (!phalcon_is_iterable(columns, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(column); PHALCON_OBS_NVAR(column_type); phalcon_array_fetch_string(&column_type, column, SL("type"), PH_NOISY_CC); if (PHALCON_IS_STRING(column_type, "scalar")) { if (!phalcon_array_isset_string(column, SS("balias"))) { PHALCON_INIT_NVAR(is_complex); ZVAL_BOOL(is_complex, 1); } PHALCON_INIT_NVAR(have_scalars); ZVAL_BOOL(have_scalars, 1); } else { PHALCON_INIT_NVAR(have_objects); ZVAL_BOOL(have_objects, 1); PHALCON_SEPARATE(number_objects); increment_function(number_objects); } zend_hash_move_forward_ex(ah1, &hp1); } /** * Check if the resultset to return is complex or simple */ if (PHALCON_IS_FALSE(is_complex)) { if (PHALCON_IS_TRUE(have_objects)) { if (PHALCON_IS_TRUE(have_scalars)) { ZVAL_BOOL(is_complex, 1); } else { if (PHALCON_IS_LONG(number_objects, 1)) { PHALCON_INIT_VAR(is_simple_std); ZVAL_BOOL(is_simple_std, 0); } else { ZVAL_BOOL(is_complex, 1); } } } else { PHALCON_INIT_NVAR(is_simple_std); ZVAL_BOOL(is_simple_std, 1); } } /** * Processing selected columns */ PHALCON_INIT_VAR(select_columns); array_init(select_columns); PHALCON_INIT_VAR(simple_column_map); array_init(simple_column_map); PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC); if (!phalcon_is_iterable(columns, &ah2, &hp2, 1, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah2, (void**) &hd, &hp2) == SUCCESS) { PHALCON_GET_FOREACH_KEY(alias, ah2, hp2); PHALCON_GET_FOREACH_VALUE(column); PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, column, SL("type"), PH_NOISY_CC); PHALCON_OBS_NVAR(sql_column); phalcon_array_fetch_string(&sql_column, column, SL("column"), PH_NOISY_CC); /** * Complete objects are treaded in a different way */ if (PHALCON_IS_STRING(type, "object")) { PHALCON_OBS_NVAR(model_name); phalcon_array_fetch_string(&model_name, column, SL("model"), PH_NOISY_CC); PHALCON_OBS_NVAR(instance); phalcon_array_fetch(&instance, models_instances, model_name, PH_NOISY_CC); PHALCON_INIT_NVAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", instance); if (PHALCON_IS_TRUE(is_complex)) { /** * If the resultset is complex we open every model into their columns */ if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_NVAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", instance); } else { PHALCON_INIT_NVAR(column_map); } if (!phalcon_is_iterable(attributes, &ah3, &hp3, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah3, (void**) &hd, &hp3) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); PHALCON_INIT_NVAR(hidden_alias); PHALCON_CONCAT_SVSV(hidden_alias, "_", sql_column, "_", attribute); PHALCON_INIT_NVAR(column_alias); array_init_size(column_alias, 3); phalcon_array_append(&column_alias, attribute, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&column_alias, sql_column, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&column_alias, hidden_alias, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&select_columns, column_alias, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah3, &hp3); } /** * We cache required meta-data to make its future access faster */ phalcon_array_update_string_multi_2(&columns, alias, SL("instance"), &instance, 0 TSRMLS_CC); phalcon_array_update_string_multi_2(&columns, alias, SL("attributes"), &attributes, 0 TSRMLS_CC); phalcon_array_update_string_multi_2(&columns, alias, SL("columnMap"), &column_map, 0 TSRMLS_CC); } else { /** * Query only the columns that are registered as attributes in the metaData */ if (!phalcon_is_iterable(attributes, &ah4, &hp4, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah4, (void**) &hd, &hp4) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); PHALCON_INIT_NVAR(column_alias); array_init_size(column_alias, 2); phalcon_array_append(&column_alias, attribute, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&column_alias, sql_column, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&select_columns, column_alias, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah4, &hp4); } } } else { /** * Create an alias if the column doesn't have one */ if (Z_TYPE_P(alias) == IS_LONG) { PHALCON_INIT_NVAR(column_alias); array_init_size(column_alias, 2); phalcon_array_append(&column_alias, sql_column, PH_SEPARATE TSRMLS_CC); add_next_index_null(column_alias); } else { PHALCON_INIT_NVAR(column_alias); array_init_size(column_alias, 3); phalcon_array_append(&column_alias, sql_column, PH_SEPARATE TSRMLS_CC); add_next_index_null(column_alias); phalcon_array_append(&column_alias, alias, PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&select_columns, column_alias, PH_SEPARATE TSRMLS_CC); } /** * Simulate a column map */ if (PHALCON_IS_FALSE(is_complex)) { if (PHALCON_IS_TRUE(is_simple_std)) { if (phalcon_array_isset_string(column, SS("sqlAlias"))) { PHALCON_OBS_NVAR(sql_alias); phalcon_array_fetch_string(&sql_alias, column, SL("sqlAlias"), PH_NOISY_CC); phalcon_array_update_zval(&simple_column_map, sql_alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&simple_column_map, alias, &alias, PH_COPY | PH_SEPARATE TSRMLS_CC); } } } zend_hash_move_forward_ex(ah2, &hp2); } zend_hash_destroy(ah2); efree(ah2); phalcon_array_update_string(&intermediate, SL("columns"), &select_columns, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * The corresponding SQL dialect generates the SQL statement based accordingly with * the database system */ PHALCON_INIT_VAR(dialect); PHALCON_CALL_METHOD(dialect, connection, "getdialect"); PHALCON_INIT_VAR(sql_select); PHALCON_CALL_METHOD_PARAMS_1(sql_select, dialect, "select", intermediate); /** * Replace the placeholders */ if (Z_TYPE_P(bind_params) == IS_ARRAY) { PHALCON_INIT_VAR(processed); array_init(processed); if (!phalcon_is_iterable(bind_params, &ah5, &hp5, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah5, (void**) &hd, &hp5) == SUCCESS) { PHALCON_GET_FOREACH_KEY(wildcard, ah5, hp5); PHALCON_GET_FOREACH_VALUE(value); if (Z_TYPE_P(wildcard) == IS_LONG) { PHALCON_INIT_NVAR(string_wildcard); PHALCON_CONCAT_SV(string_wildcard, ":", wildcard); phalcon_array_update_zval(&processed, string_wildcard, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&processed, wildcard, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah5, &hp5); } } else { PHALCON_CPY_WRT(processed, bind_params); } /** * Replace the bind Types */ if (Z_TYPE_P(bind_types) == IS_ARRAY) { PHALCON_INIT_VAR(processed_types); array_init(processed_types); if (!phalcon_is_iterable(bind_types, &ah6, &hp6, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah6, (void**) &hd, &hp6) == SUCCESS) { PHALCON_GET_FOREACH_KEY(wildcard, ah6, hp6); PHALCON_GET_FOREACH_VALUE(value); if (Z_TYPE_P(wildcard) == IS_LONG) { PHALCON_INIT_NVAR(string_wildcard); PHALCON_CONCAT_SV(string_wildcard, ":", wildcard); phalcon_array_update_zval(&processed_types, string_wildcard, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&processed_types, wildcard, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah6, &hp6); } } else { PHALCON_CPY_WRT(processed_types, bind_types); } /** * Execute the query */ PHALCON_INIT_VAR(result); PHALCON_CALL_METHOD_PARAMS_3(result, connection, "query", sql_select, processed, processed_types); PHALCON_INIT_VAR(count); PHALCON_CALL_METHOD_PARAMS_1(count, result, "numrows", result); if (zend_is_true(count)) { PHALCON_CPY_WRT(result_data, result); } else { PHALCON_INIT_VAR(result_data); ZVAL_BOOL(result_data, 0); } /** * Choose a resultset type */ PHALCON_OBS_VAR(cache); phalcon_read_property(&cache, this_ptr, SL("_cache"), PH_NOISY_CC); if (PHALCON_IS_FALSE(is_complex)) { /** * Select the base object */ if (PHALCON_IS_TRUE(is_simple_std)) { PHALCON_INIT_VAR(result_object); object_init_ex(result_object, phalcon_mvc_model_row_ce); } else { PHALCON_CPY_WRT(result_object, model); PHALCON_INIT_NVAR(simple_column_map); PHALCON_CALL_METHOD_PARAMS_1(simple_column_map, meta_data, "getcolumnmap", model); } /** * Simple resultsets contains only complete objects */ PHALCON_INIT_VAR(resultset); object_init_ex(resultset, phalcon_mvc_model_resultset_simple_ce); PHALCON_CALL_METHOD_PARAMS_4_NORETURN(resultset, "__construct", simple_column_map, result_object, result_data, cache); RETURN_CTOR(resultset); } /** * Complex resultsets may contain complete objects and scalars */ PHALCON_INIT_NVAR(resultset); object_init_ex(resultset, phalcon_mvc_model_resultset_complex_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(resultset, "__construct", columns, result_data, cache); RETURN_CTOR(resultset); } /** * Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return Phalcon\Mvc\Model\Query\StatusInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, _executeInsert){ zval *intermediate, *bind_params, *bind_types; zval *model_name, *manager, *models_instances; zval *model = NULL, *connection, *meta_data, *attributes; zval *automatic_fields = NULL, *fields = NULL, *column_map = NULL; zval *values, *number_fields, *number_values; zval *dialect, *double_colon, *empty_string; zval *null_value, *not_exists, *insert_values; zval *value = NULL, *number = NULL, *type = NULL, *expr_value = NULL, *insert_value = NULL; zval *insert_expr = NULL, *wildcard = NULL, *exception_message = NULL; zval *field_name = NULL, *attribute_name = NULL, *base_model; zval *insert_model, *success, *status; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &intermediate, &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(model_name); phalcon_array_fetch_string(&model_name, intermediate, SL("model"), PH_NOISY_CC); PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); if (phalcon_array_isset(models_instances, model_name)) { PHALCON_OBS_VAR(model); phalcon_array_fetch(&model, models_instances, model_name, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); } /** * Get the model connection */ PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, model, "getconnection"); PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_metaData"), PH_NOISY_CC); PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", model); PHALCON_INIT_VAR(automatic_fields); ZVAL_BOOL(automatic_fields, 0); /** * The 'fields' index may already have the fields to be used in the query */ if (phalcon_array_isset_string(intermediate, SS("fields"))) { PHALCON_OBS_VAR(fields); phalcon_array_fetch_string(&fields, intermediate, SL("fields"), PH_NOISY_CC); } else { ZVAL_BOOL(automatic_fields, 1); PHALCON_CPY_WRT(fields, attributes); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", model); } else { PHALCON_INIT_NVAR(column_map); } } PHALCON_OBS_VAR(values); phalcon_array_fetch_string(&values, intermediate, SL("values"), PH_NOISY_CC); PHALCON_INIT_VAR(number_fields); phalcon_fast_count(number_fields, fields TSRMLS_CC); PHALCON_INIT_VAR(number_values); phalcon_fast_count(number_values, values TSRMLS_CC); /** * The number of calculated values must be equal to the number of fields in the * model */ if (!PHALCON_IS_EQUAL(number_fields, number_values)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The column count does not match the values count"); return; } /** * Get the dialect to resolve the SQL expressions */ PHALCON_INIT_VAR(dialect); PHALCON_CALL_METHOD(dialect, connection, "getdialect"); PHALCON_INIT_VAR(double_colon); ZVAL_STRING(double_colon, ":", 1); PHALCON_INIT_VAR(empty_string); ZVAL_STRING(empty_string, "", 1); PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(not_exists); ZVAL_BOOL(not_exists, 0); PHALCON_INIT_VAR(insert_values); array_init(insert_values); if (!phalcon_is_iterable(values, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(number, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, value, SL("type"), PH_NOISY_CC); PHALCON_OBS_NVAR(expr_value); phalcon_array_fetch_string(&expr_value, value, SL("value"), PH_NOISY_CC); switch (phalcon_get_intval(type)) { case 260: PHALCON_INIT_NVAR(insert_value); PHALCON_CALL_METHOD_PARAMS_1(insert_value, dialect, "getsqlexpression", expr_value); break; case 258: PHALCON_INIT_NVAR(insert_value); PHALCON_CALL_METHOD_PARAMS_1(insert_value, dialect, "getsqlexpression", expr_value); break; case 259: PHALCON_INIT_NVAR(insert_value); PHALCON_CALL_METHOD_PARAMS_1(insert_value, dialect, "getsqlexpression", expr_value); break; case 322: PHALCON_CPY_WRT(insert_value, null_value); break; case 273: if (Z_TYPE_P(bind_params) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Bound parameter cannot be replaced because placeholders is not an array"); return; } PHALCON_INIT_NVAR(insert_expr); PHALCON_CALL_METHOD_PARAMS_1(insert_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(wildcard); phalcon_fast_str_replace(wildcard, double_colon, empty_string, insert_expr TSRMLS_CC); if (phalcon_array_isset(bind_params, wildcard)) { PHALCON_OBS_NVAR(insert_value); phalcon_array_fetch(&insert_value, bind_params, wildcard, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Bound parameter '", wildcard, "' cannot be replaced because it's not in the placeholders list"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } break; case 274: if (Z_TYPE_P(bind_params) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Bound parameter cannot be replaced because placeholders is not an array"); return; } PHALCON_INIT_NVAR(insert_expr); PHALCON_CALL_METHOD_PARAMS_1(insert_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(wildcard); phalcon_fast_str_replace(wildcard, double_colon, empty_string, insert_expr TSRMLS_CC); if (phalcon_array_isset(bind_params, wildcard)) { PHALCON_OBS_NVAR(insert_value); phalcon_array_fetch(&insert_value, bind_params, wildcard, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Bound parameter '", wildcard, "' cannot be replaced because it's not in the placeholders list"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } break; default: PHALCON_INIT_NVAR(insert_expr); PHALCON_CALL_METHOD_PARAMS_1(insert_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(insert_value); object_init_ex(insert_value, phalcon_db_rawvalue_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(insert_value, "__construct", insert_expr); break; } PHALCON_OBS_NVAR(field_name); phalcon_array_fetch(&field_name, fields, number, PH_NOISY_CC); /** * If the user didn't defined a column list we assume all the model's attributes as * columns */ if (PHALCON_IS_TRUE(automatic_fields)) { if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field_name)) { PHALCON_OBS_NVAR(attribute_name); phalcon_array_fetch(&attribute_name, column_map, field_name, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field_name, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_name, field_name); } } else { PHALCON_CPY_WRT(attribute_name, field_name); } phalcon_array_update_zval(&insert_values, attribute_name, &insert_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * Get a base model from the Models Manager */ PHALCON_INIT_VAR(base_model); PHALCON_CALL_METHOD_PARAMS_1(base_model, manager, "load", model_name); /** * Clone the base model */ PHALCON_INIT_VAR(insert_model); if (phalcon_clone(insert_model, base_model TSRMLS_CC) == FAILURE) { return; } /** * Call 'create' to ensure that an insert is performed */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_1(success, insert_model, "create", insert_values); /** * Return the insertation status */ PHALCON_INIT_VAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, insert_model); RETURN_CTOR(status); } /** * Query the records on which the UPDATE/DELETE operation well be done * * @param Phalcon\Mvc\Model $model * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, _getRelatedRecords){ zval *model, *intermediate, *bind_params, *bind_types; zval *selected_tables, *selected_models, *source; zval *model_name, *select_column, *selected_columns; zval *select_ir, *where_conditions, *limit_conditions; zval *type_select, *dependency_injector, *query; zval *records; zval *a0 = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzz", &model, &intermediate, &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(selected_tables); phalcon_array_fetch_string(&selected_tables, intermediate, SL("tables"), PH_NOISY_CC); PHALCON_OBS_VAR(selected_models); phalcon_array_fetch_string(&selected_models, intermediate, SL("models"), PH_NOISY_CC); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, model, "getsource"); PHALCON_INIT_VAR(model_name); phalcon_get_class(model_name, model, 0 TSRMLS_CC); PHALCON_INIT_VAR(select_column); array_init_size(select_column, 1); PHALCON_INIT_VAR(a0); array_init_size(a0, 3); add_assoc_stringl_ex(a0, SS("type"), SL("object"), 1); phalcon_array_update_string(&a0, SL("model"), &model_name, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&a0, SL("column"), &source, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_append(&select_column, a0, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(selected_columns); array_init_size(selected_columns, 1); phalcon_array_append(&selected_columns, select_column, PH_SEPARATE TSRMLS_CC); /** * Instead of create a PQHL string statement we manually create the IR * representation */ PHALCON_INIT_VAR(select_ir); array_init_size(select_ir, 3); phalcon_array_update_string(&select_ir, SL("columns"), &select_column, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&select_ir, SL("models"), &selected_models, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&select_ir, SL("tables"), &selected_tables, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Check if a WHERE clause was especified */ if (phalcon_array_isset_string(intermediate, SS("where"))) { PHALCON_OBS_VAR(where_conditions); phalcon_array_fetch_string(&where_conditions, intermediate, SL("where"), PH_NOISY_CC); phalcon_array_update_string(&select_ir, SL("where"), &where_conditions, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Check if a WHERE clause was especified */ if (phalcon_array_isset_string(intermediate, SS("limit"))) { PHALCON_OBS_VAR(limit_conditions); phalcon_array_fetch_string(&limit_conditions, intermediate, SL("limit"), PH_NOISY_CC); phalcon_array_update_string(&select_ir, SL("limit"), &limit_conditions, PH_COPY | PH_SEPARATE TSRMLS_CC); } PHALCON_INIT_VAR(type_select); ZVAL_LONG(type_select, 309); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); /** * We create another Phalcon\Mvc\Model\Query to get the related records */ PHALCON_INIT_VAR(query); object_init_ex(query, phalcon_mvc_model_query_ce); PHALCON_CALL_METHOD_NORETURN(query, "__construct"); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "setdi", dependency_injector); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "settype", type_select); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "setintermediate", select_ir); PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD_PARAMS_2(records, query, "execute", bind_params, bind_types); RETURN_CCTOR(records); } /** * Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return Phalcon\Mvc\Model\Query\StatusInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, _executeUpdate){ zval *intermediate, *bind_params, *bind_types; zval *models, *model_name, *models_instances; zval *model = NULL, *manager, *connection, *dialect, *double_colon; zval *empty_string, *fields, *values, *update_values; zval *select_bind_params = NULL, *select_bind_types = NULL; zval *null_value, *field = NULL, *number = NULL, *field_name = NULL; zval *value = NULL, *type = NULL, *expr_value = NULL, *update_value = NULL; zval *update_expr = NULL, *wildcard = NULL, *exception_message = NULL; zval *records, *success = NULL, *status = NULL, *record = NULL; zval *r0 = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &intermediate, &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models); phalcon_array_fetch_string(&models, intermediate, SL("models"), PH_NOISY_CC); if (phalcon_array_isset_long(models, 1)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Updating several models at the same time is still not supported"); return; } PHALCON_OBS_VAR(model_name); phalcon_array_fetch_long(&model_name, models, 0, PH_NOISY_CC); /** * Load the model from the modelsManager or from the _modelsInstances property */ PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); if (phalcon_array_isset(models_instances, model_name)) { PHALCON_OBS_VAR(model); phalcon_array_fetch(&model, models_instances, model_name, PH_NOISY_CC); } else { PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); } PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, model, "getconnection"); PHALCON_INIT_VAR(dialect); PHALCON_CALL_METHOD(dialect, connection, "getdialect"); PHALCON_INIT_VAR(double_colon); ZVAL_STRING(double_colon, ":", 1); PHALCON_INIT_VAR(empty_string); ZVAL_STRING(empty_string, "", 1); PHALCON_OBS_VAR(fields); phalcon_array_fetch_string(&fields, intermediate, SL("fields"), PH_NOISY_CC); PHALCON_OBS_VAR(values); phalcon_array_fetch_string(&values, intermediate, SL("values"), PH_NOISY_CC); /** * update_values is applied to every record */ PHALCON_INIT_VAR(update_values); array_init(update_values); /** * If a placeholder is unused in the update values, we assume that it's used in the * SELECT */ PHALCON_CPY_WRT(select_bind_params, bind_params); PHALCON_CPY_WRT(select_bind_types, bind_types); PHALCON_INIT_VAR(null_value); if (!phalcon_is_iterable(fields, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(number, ah0, hp0); PHALCON_GET_FOREACH_VALUE(field); PHALCON_OBS_NVAR(field_name); phalcon_array_fetch_string(&field_name, field, SL("name"), PH_NOISY_CC); PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, values, number, PH_NOISY_CC); PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, value, SL("type"), PH_NOISY_CC); PHALCON_OBS_NVAR(expr_value); phalcon_array_fetch_string(&expr_value, value, SL("value"), PH_NOISY_CC); switch (phalcon_get_intval(type)) { case 260: PHALCON_INIT_NVAR(update_value); PHALCON_CALL_METHOD_PARAMS_1(update_value, dialect, "getsqlexpression", expr_value); break; case 258: PHALCON_INIT_NVAR(update_value); PHALCON_CALL_METHOD_PARAMS_1(update_value, dialect, "getsqlexpression", expr_value); break; case 259: PHALCON_INIT_NVAR(update_value); PHALCON_CALL_METHOD_PARAMS_1(update_value, dialect, "getsqlexpression", expr_value); break; case 322: PHALCON_CPY_WRT(update_value, null_value); break; case 273: if (Z_TYPE_P(bind_params) == IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Bound parameter cannot be replaced because placeholders is not an array"); return; } PHALCON_INIT_NVAR(update_expr); PHALCON_CALL_METHOD_PARAMS_1(update_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(wildcard); phalcon_fast_str_replace(wildcard, double_colon, empty_string, update_expr TSRMLS_CC); if (phalcon_array_isset(bind_params, wildcard)) { PHALCON_OBS_NVAR(update_value); phalcon_array_fetch(&update_value, bind_params, wildcard, PH_NOISY_CC); PHALCON_SEPARATE(select_bind_params); phalcon_array_unset(select_bind_params, wildcard); PHALCON_SEPARATE(select_bind_types); phalcon_array_unset(select_bind_types, wildcard); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Bound parameter '", wildcard, "' cannot be replaced because it's not in the placeholders list"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } break; case 274: if (Z_TYPE_P(bind_params) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Bound parameter cannot be replaced because placeholders is not an array"); return; } PHALCON_INIT_NVAR(update_expr); PHALCON_CALL_METHOD_PARAMS_1(update_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(wildcard); phalcon_fast_str_replace(wildcard, double_colon, empty_string, update_expr TSRMLS_CC); if (phalcon_array_isset(bind_params, wildcard)) { PHALCON_OBS_NVAR(update_value); phalcon_array_fetch(&update_value, bind_params, wildcard, PH_NOISY_CC); PHALCON_SEPARATE(select_bind_params); phalcon_array_unset(select_bind_params, wildcard); PHALCON_SEPARATE(select_bind_types); phalcon_array_unset(select_bind_types, wildcard); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Bound parameter '", wildcard, "' cannot be replaced because it's not in the placeholders list"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } break; default: PHALCON_INIT_NVAR(update_expr); PHALCON_CALL_METHOD_PARAMS_1(update_expr, dialect, "getsqlexpression", expr_value); PHALCON_INIT_NVAR(update_value); object_init_ex(update_value, phalcon_db_rawvalue_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(update_value, "__construct", update_expr); break; } phalcon_array_update_zval(&update_values, field_name, &update_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } /** * We need to query the records related to the update */ PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD_PARAMS_4(records, this_ptr, "_getrelatedrecords", model, intermediate, select_bind_params, select_bind_types); /** * If there are no records to apply the update we return success */ if (!phalcon_fast_count_ev(records TSRMLS_CC)) { PHALCON_INIT_VAR(success); ZVAL_BOOL(success, 1); PHALCON_INIT_VAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, null_value); RETURN_CTOR(status); } PHALCON_CALL_METHOD_NORETURN(records, "rewind"); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, records, "valid"); if (PHALCON_IS_NOT_FALSE(r0)) { } else { break; } PHALCON_INIT_NVAR(record); PHALCON_CALL_METHOD(record, records, "current"); /** * We apply the executed values to every record found */ PHALCON_INIT_NVAR(success); PHALCON_CALL_METHOD_PARAMS_1(success, record, "update", update_values); if (!zend_is_true(success)) { PHALCON_INIT_NVAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, record); RETURN_CTOR(status); } /** * Move the cursor to the next record */ PHALCON_CALL_METHOD_NORETURN(records, "next"); } PHALCON_INIT_NVAR(success); ZVAL_BOOL(success, 1); PHALCON_INIT_NVAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, null_value); RETURN_CTOR(status); } /** * Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status * * @param array $intermediate * @param array $bindParams * @param array $bindTypes * @return Phalcon\Mvc\Model\Query\StatusInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, _executeDelete){ zval *intermediate, *bind_params, *bind_types; zval *models, *model_name, *models_instances; zval *model = NULL, *manager, *records, *success = NULL, *null_value = NULL; zval *status = NULL, *record = NULL; zval *r0 = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &intermediate, &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models); phalcon_array_fetch_string(&models, intermediate, SL("models"), PH_NOISY_CC); if (phalcon_array_isset_long(models, 1)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Delete from several models at the same time is still not supported"); return; } PHALCON_OBS_VAR(model_name); phalcon_array_fetch_long(&model_name, models, 0, PH_NOISY_CC); /** * Load the model from the modelsManager or from the _modelsInstances property */ PHALCON_OBS_VAR(models_instances); phalcon_read_property(&models_instances, this_ptr, SL("_modelsInstances"), PH_NOISY_CC); if (phalcon_array_isset(models_instances, model_name)) { PHALCON_OBS_VAR(model); phalcon_array_fetch(&model, models_instances, model_name, PH_NOISY_CC); } else { PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_manager"), PH_NOISY_CC); PHALCON_INIT_NVAR(model); PHALCON_CALL_METHOD_PARAMS_1(model, manager, "load", model_name); } /** * Get the records to be deleted */ PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD_PARAMS_4(records, this_ptr, "_getrelatedrecords", model, intermediate, bind_params, bind_types); /** * If there are no records to delete we return success */ if (!phalcon_fast_count_ev(records TSRMLS_CC)) { PHALCON_INIT_VAR(success); ZVAL_BOOL(success, 1); PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, null_value); RETURN_CTOR(status); } PHALCON_CALL_METHOD_NORETURN(records, "rewind"); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, records, "valid"); if (PHALCON_IS_NOT_FALSE(r0)) { } else { break; } PHALCON_INIT_NVAR(record); PHALCON_CALL_METHOD(record, records, "current"); /** * We delete every record found */ PHALCON_INIT_NVAR(success); PHALCON_CALL_METHOD(success, record, "delete"); if (!zend_is_true(success)) { PHALCON_INIT_NVAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, record); RETURN_CTOR(status); } /** * Move the cursor to the next record */ PHALCON_CALL_METHOD_NORETURN(records, "next"); } PHALCON_INIT_NVAR(success); ZVAL_BOOL(success, 1); PHALCON_INIT_NVAR(null_value); ZVAL_BOOL(null_value, 1); /** * Create a status to report the deletion status */ PHALCON_INIT_NVAR(status); object_init_ex(status, phalcon_mvc_model_query_status_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(status, "__construct", success, null_value); RETURN_CTOR(status); } /** * Executes a parsed PHQL statement * * @param array $bindParams * @param array $bindTypes * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model_Query, execute){ zval *bind_params = NULL, *bind_types = NULL, *unique_row; zval *cache_options, *key, *lifetime = NULL, *cache_service = NULL; zval *dependency_injector, *cache, *result = NULL, *is_fresh; zval *prepared_result = NULL, *intermediate, *type; zval *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } if (!bind_params) { PHALCON_INIT_VAR(bind_params); } if (!bind_types) { PHALCON_INIT_VAR(bind_types); } PHALCON_OBS_VAR(unique_row); phalcon_read_property(&unique_row, this_ptr, SL("_uniqueRow"), PH_NOISY_CC); PHALCON_OBS_VAR(cache_options); phalcon_read_property(&cache_options, this_ptr, SL("_cacheOptions"), PH_NOISY_CC); if (Z_TYPE_P(cache_options) != IS_NULL) { if (Z_TYPE_P(cache_options) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid caching options"); return; } /** * The user must set a cache key */ if (phalcon_array_isset_string(cache_options, SS("key"))) { PHALCON_OBS_VAR(key); phalcon_array_fetch_string(&key, cache_options, SL("key"), PH_NOISY_CC); } else { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A cache key must be provided to identify the cached resultset in the cache backend"); return; } /** * By defaut use use 3600 seconds (1 hour) as cache lifetime */ if (phalcon_array_isset_string(cache_options, SS("lifetime"))) { PHALCON_OBS_VAR(lifetime); phalcon_array_fetch_string(&lifetime, cache_options, SL("lifetime"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(lifetime); ZVAL_LONG(lifetime, 3600); } /** * 'modelsCache' is the default name for the models cache service */ if (phalcon_array_isset_string(cache_options, SS("service"))) { PHALCON_OBS_VAR(cache_service); phalcon_array_fetch_string(&cache_service, cache_options, SL("service"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(cache_service); ZVAL_STRING(cache_service, "modelsCache", 1); } PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); PHALCON_INIT_VAR(cache); PHALCON_CALL_METHOD_PARAMS_1(cache, dependency_injector, "getshared", cache_service); if (Z_TYPE_P(cache) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The cache service must be an object"); return; } PHALCON_INIT_VAR(result); PHALCON_CALL_METHOD_PARAMS_2(result, cache, "get", key, lifetime); if (Z_TYPE_P(result) != IS_NULL) { if (Z_TYPE_P(result) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The cache didn't return a valid resultset"); return; } PHALCON_INIT_VAR(is_fresh); ZVAL_BOOL(is_fresh, 0); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(result, "setisfresh", is_fresh); /** * Check if only the first row must be returned */ if (zend_is_true(unique_row)) { PHALCON_INIT_VAR(prepared_result); PHALCON_CALL_METHOD(prepared_result, result, "getfirst"); } else { PHALCON_CPY_WRT(prepared_result, result); } RETURN_CCTOR(prepared_result); } phalcon_update_property_zval(this_ptr, SL("_cache"), cache TSRMLS_CC); } /** * The statement is parsed from its PHQL string or a previously processed IR */ PHALCON_INIT_VAR(intermediate); PHALCON_CALL_METHOD(intermediate, this_ptr, "parse"); PHALCON_OBS_VAR(type); phalcon_read_property(&type, this_ptr, SL("_type"), PH_NOISY_CC); switch (phalcon_get_intval(type)) { case 309: PHALCON_INIT_NVAR(result); PHALCON_CALL_METHOD_PARAMS_3(result, this_ptr, "_executeselect", intermediate, bind_params, bind_types); break; case 306: PHALCON_INIT_NVAR(result); PHALCON_CALL_METHOD_PARAMS_3(result, this_ptr, "_executeinsert", intermediate, bind_params, bind_types); break; case 300: PHALCON_INIT_NVAR(result); PHALCON_CALL_METHOD_PARAMS_3(result, this_ptr, "_executeupdate", intermediate, bind_params, bind_types); break; case 303: PHALCON_INIT_NVAR(result); PHALCON_CALL_METHOD_PARAMS_3(result, this_ptr, "_executedelete", intermediate, bind_params, bind_types); break; default: PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Unknown statement ", type); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * We store the resultset in the cache if any */ if (Z_TYPE_P(cache_options) != IS_NULL) { /** * Only PHQL SELECTs can be cached */ if (!PHALCON_IS_LONG(type, 309)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Only PHQL statements that return resultsets can be cached"); return; } PHALCON_CALL_METHOD_PARAMS_3_NORETURN(cache, "save", key, result, lifetime); } /** * Check if only the first row must be returned */ if (zend_is_true(unique_row)) { PHALCON_INIT_NVAR(prepared_result); PHALCON_CALL_METHOD(prepared_result, result, "getfirst"); } else { PHALCON_CPY_WRT(prepared_result, result); } RETURN_CCTOR(prepared_result); } /** * Executes the query returning the first result * * @param array $bindParams * @param array $bindTypes * @return Ṕhalcon\Mvc\ModelInterface */ PHP_METHOD(Phalcon_Mvc_Model_Query, getSingleResult){ zval *bind_params = NULL, *bind_types = NULL, *unique_row; zval *result = NULL, *first_result; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &bind_params, &bind_types) == FAILURE) { RETURN_MM_NULL(); } if (!bind_params) { PHALCON_INIT_VAR(bind_params); } if (!bind_types) { PHALCON_INIT_VAR(bind_types); } PHALCON_OBS_VAR(unique_row); phalcon_read_property(&unique_row, this_ptr, SL("_uniqueRow"), PH_NOISY_CC); /** * The query is already programmed to return just one row */ if (zend_is_true(unique_row)) { PHALCON_INIT_VAR(result); PHALCON_CALL_METHOD_PARAMS_2(result, this_ptr, "execute", bind_params, bind_types); RETURN_CCTOR(result); } PHALCON_INIT_NVAR(result); PHALCON_CALL_METHOD_PARAMS_2(result, this_ptr, "execute", bind_params, bind_types); PHALCON_INIT_VAR(first_result); PHALCON_CALL_METHOD(first_result, result, "getfirst"); RETURN_CCTOR(result); } /** * Sets the type of PHQL statement to be executed * * @param int $type * @return Phalcon\Mvc\Model\Query */ PHP_METHOD(Phalcon_Mvc_Model_Query, setType){ zval *type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &type) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_type"), type TSRMLS_CC); RETURN_THISW(); } /** * Gets the type of PHQL statement executed * * @return int */ PHP_METHOD(Phalcon_Mvc_Model_Query, getType){ RETURN_MEMBER(this_ptr, "_type"); } /** * Allows to set the IR to be executed * * @param array $intermediate * @return Phalcon\Mvc\Model\Query */ PHP_METHOD(Phalcon_Mvc_Model_Query, setIntermediate){ zval *intermediate; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &intermediate) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_intermediate"), intermediate TSRMLS_CC); RETURN_THISW(); } /** * Returns the intermediate representation of the PHQL statement * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Query, getIntermediate){ RETURN_MEMBER(this_ptr, "_intermediate"); }
tmihalik/cphalcon
ext/cli/router.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/array.h" #include "kernel/string.h" #include "kernel/object.h" /** * Phalcon\CLI\Router * * <p>Phalcon\CLI\Router is the standard framework router. Routing is the * process of taking a command-line arguments and * decomposing it into parameters to determine which module, task, and * action of that task should receive the request</p> * *<code> * $router = new Phalcon\CLI\Router(); * $router->handle(array()); * echo $router->getTaskName(); *</code> * */ /** * Phalcon\CLI\Router initializer */ PHALCON_INIT_CLASS(Phalcon_CLI_Router){ PHALCON_REGISTER_CLASS(Phalcon\\CLI, Router, cli_router, phalcon_cli_router_method_entry, 0); zend_declare_property_null(phalcon_cli_router_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_module"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_task"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_action"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_params"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_defaultModule"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_defaultTask"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_defaultAction"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cli_router_ce, SL("_defaultParams"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_cli_router_ce TSRMLS_CC, 1, phalcon_di_injectionawareinterface_ce); return SUCCESS; } /** * Phalcon\CLI\Router constructor */ PHP_METHOD(Phalcon_CLI_Router, __construct){ phalcon_update_property_empty_array(phalcon_cli_router_ce, this_ptr, SL("_params") TSRMLS_CC); phalcon_update_property_empty_array(phalcon_cli_router_ce, this_ptr, SL("_defaultParams") TSRMLS_CC); } /** * Sets the dependency injector * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_CLI_Router, setDI){ zval *dependency_injector; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); } /** * Returns the internal dependency injector * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_CLI_Router, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Sets the name of the default module * * @param string $moduleName */ PHP_METHOD(Phalcon_CLI_Router, setDefaultModule){ zval *module_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &module_name) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_defaultModule"), module_name TSRMLS_CC); } /** * Sets the default controller name * * @param string $taskName */ PHP_METHOD(Phalcon_CLI_Router, setDefaultTask){ zval *task_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &task_name) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_defaultTask"), task_name TSRMLS_CC); } /** * Sets the default action name * * @param string $actionName */ PHP_METHOD(Phalcon_CLI_Router, setDefaultAction){ zval *action_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &action_name) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_defaultAction"), action_name TSRMLS_CC); } /** * Handles routing information received from command-line arguments * * @param array $arguments */ PHP_METHOD(Phalcon_CLI_Router, handle){ int i; zval *arguments = NULL, *arguments_count, *params, *arg = NULL; zval *module_name, *default_module; zval *task_name, *default_task, *task_name_tmp, *task_name_parts; zval *delimiter, *status; zval *action_name, *default_action; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &arguments) == FAILURE) { PHALCON_MM_RESTORE(); RETURN_NULL(); } if (!arguments) { PHALCON_INIT_VAR(arguments); array_init(arguments); } if (Z_TYPE_P(arguments) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_cli_router_exception_ce, "Arguments must be an Array"); return; } /* * process arguments */ // initial and set default to null PHALCON_INIT_VAR(module_name); PHALCON_INIT_VAR(task_name); PHALCON_INIT_VAR(task_name_tmp); PHALCON_INIT_VAR(action_name); PHALCON_INIT_VAR(params); PHALCON_INIT_VAR(delimiter); array_init(params); phalcon_update_property_zval(this_ptr, SL("_module"), module_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_task"), task_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_action"), action_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_params"), params TSRMLS_CC); ZVAL_STRING(delimiter, ":", 1); PHALCON_INIT_VAR(arguments_count); phalcon_fast_count(arguments_count, arguments TSRMLS_CC); if (Z_LVAL_P(arguments_count) > 3) { // script, task, action, params..... phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC); phalcon_array_fetch_long(&action_name, arguments, 2, PH_NOISY_CC); // process params for (i = 3; i < Z_LVAL_P(arguments_count); i++) { PHALCON_INIT_NVAR(arg); phalcon_array_fetch_long(&arg, arguments, i, PH_NOISY_CC); phalcon_array_append(&params, arg, PH_SEPARATE TSRMLS_CC); } } else { if (Z_LVAL_P(arguments_count) > 2) { // script, task, action phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC); phalcon_array_fetch_long(&action_name, arguments, 2, PH_NOISY_CC); } else { if (Z_LVAL_P(arguments_count) > 1) { // script, task phalcon_array_fetch_long(&task_name_tmp, arguments, 1, PH_NOISY_CC); } } } // if task_name settings, parse task_name for module_name if (Z_TYPE_P(task_name_tmp) != IS_NULL) { PHALCON_INIT_VAR(task_name_parts); phalcon_fast_explode(task_name_parts, delimiter, task_name_tmp TSRMLS_CC); PHALCON_INIT_VAR(status); phalcon_fast_count(status, task_name_parts TSRMLS_CC); if (Z_LVAL_P(status) == 2) { PHALCON_INIT_NVAR(module_name); PHALCON_INIT_NVAR(task_name); phalcon_array_fetch_long(&module_name, task_name_parts, 0, PH_NOISY_CC); phalcon_array_fetch_long(&task_name, task_name_parts, 1, PH_NOISY_CC); }else { PHALCON_INIT_NVAR(task_name); phalcon_array_fetch_long(&task_name, task_name_parts, 0, PH_NOISY_CC); } } // update properties if (Z_TYPE_P(module_name) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_module"), module_name TSRMLS_CC); } else { PHALCON_OBS_VAR(default_module); phalcon_read_property(&default_module, this_ptr, SL("_defaultModule"), PH_NOISY_CC); if (Z_TYPE_P(default_module) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_module"), default_module TSRMLS_CC); } } PHALCON_OBS_NVAR(module_name); phalcon_read_property(&module_name, this_ptr, SL("_module"), PH_NOISY_CC); if (Z_TYPE_P(task_name) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_task"), task_name TSRMLS_CC); } else { PHALCON_OBS_VAR(default_task); phalcon_read_property(&default_task, this_ptr, SL("_defaultTask"), PH_NOISY_CC); if (Z_TYPE_P(default_task) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_task"), default_task TSRMLS_CC); } } PHALCON_OBS_NVAR(task_name); phalcon_read_property(&task_name, this_ptr, SL("_task"), PH_NOISY_CC); if (Z_TYPE_P(action_name) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_action"), action_name TSRMLS_CC); } else { PHALCON_OBS_VAR(default_action); phalcon_read_property(&default_action, this_ptr, SL("_defaultAction"), PH_NOISY_CC); if (Z_TYPE_P(default_action) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_action"), default_action TSRMLS_CC); } } phalcon_update_property_zval(this_ptr, SL("_params"), params TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns proccesed module name * * @return string */ PHP_METHOD(Phalcon_CLI_Router, getModuleName){ RETURN_MEMBER(this_ptr, "_module"); } /** * Returns proccesed task name * * @return string */ PHP_METHOD(Phalcon_CLI_Router, getTaskName){ RETURN_MEMBER(this_ptr, "_task"); } /** * Returns proccesed action name * * @return string */ PHP_METHOD(Phalcon_CLI_Router, getActionName){ RETURN_MEMBER(this_ptr, "_action"); } /** * Returns proccesed extra params * * @return array */ PHP_METHOD(Phalcon_CLI_Router, getParams){ RETURN_MEMBER(this_ptr, "_params"); }
tmihalik/cphalcon
ext/di/service/builder.c
<reponame>tmihalik/cphalcon /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/concat.h" #include "kernel/exception.h" #include "kernel/array.h" #include "kernel/operators.h" #include "kernel/fcall.h" #include "kernel/file.h" #include "kernel/object.h" /** * Phalcon\DI\Service\Builder * * This class builds instances based on complex definitions */ /** * Phalcon\DI\Service\Builder initializer */ PHALCON_INIT_CLASS(Phalcon_DI_Service_Builder){ PHALCON_REGISTER_CLASS(Phalcon\\DI\\Service, Builder, di_service_builder, phalcon_di_service_builder_method_entry, 0); return SUCCESS; } /** * Resolves a constructor/call parameter * * @param Phalcon\DiInterface $dependencyInjector * @param int $position * @param array $argument * @return mixed */ PHP_METHOD(Phalcon_DI_Service_Builder, _buildParameter){ zval *dependency_injector, *position, *argument; zval *exception_message = NULL, *type, *name = NULL, *value = NULL, *instance_arguments; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &dependency_injector, &position, &argument) == FAILURE) { RETURN_MM_NULL(); } /** * All the arguments must be an array */ if (Z_TYPE_P(argument) != IS_ARRAY) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Argument at position ", position, " must be an array"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } /** * All the arguments must have a type */ if (!phalcon_array_isset_string(argument, SS("type"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Argument at position ", position, " must have a type"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } PHALCON_OBS_VAR(type); phalcon_array_fetch_string(&type, argument, SL("type"), PH_NOISY_CC); /** * If the argument type is 'service', we obtain the service from the DI */ if (PHALCON_IS_STRING(type, "service")) { if (!phalcon_array_isset_string(argument, SS("name"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Service 'name' is required in parameter on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "The dependency injector container is not valid"); return; } PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, argument, SL("name"), PH_NOISY_CC); PHALCON_INIT_VAR(value); PHALCON_CALL_METHOD_PARAMS_1(value, dependency_injector, "get", name); RETURN_CCTOR(value); } /** * If the argument type is 'parameter', we assign the value as it is */ if (PHALCON_IS_STRING(type, "parameter")) { if (!phalcon_array_isset_string(argument, SS("value"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Service 'value' is required in parameter on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, argument, SL("value"), PH_NOISY_CC); RETURN_CCTOR(value); } /** * If the argument type is 'instance', we assign the value as it is */ if (PHALCON_IS_STRING(type, "instance")) { if (!phalcon_array_isset_string(argument, SS("className"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Service 'className' is required in parameter on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "The dependency injector container is not valid"); return; } PHALCON_OBS_NVAR(name); phalcon_array_fetch_string(&name, argument, SL("className"), PH_NOISY_CC); if (!phalcon_array_isset_string(argument, SS("arguments"))) { /** * The instance parameter does not have arguments for its constructor */ PHALCON_INIT_NVAR(value); PHALCON_CALL_METHOD_PARAMS_1(value, dependency_injector, "get", name); } else { PHALCON_OBS_VAR(instance_arguments); phalcon_array_fetch_string(&instance_arguments, argument, SL("arguments"), PH_NOISY_CC); /** * Build the instance with arguments */ PHALCON_INIT_NVAR(value); PHALCON_CALL_METHOD_PARAMS_2(value, dependency_injector, "get", name, instance_arguments); } RETURN_CCTOR(value); } /** * Unknown parameter type */ PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Unknown service type in parameter on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } /** * Resolves an array of parameters * * @param Phalcon\DiInterface $dependencyInjector * @param array $arguments * @return arguments */ PHP_METHOD(Phalcon_DI_Service_Builder, _buildParameters){ zval *dependency_injector, *arguments, *build_arguments; zval *argument = NULL, *position = NULL, *value = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &dependency_injector, &arguments) == FAILURE) { RETURN_MM_NULL(); } /** * The arguments group must be an array of arrays */ if (Z_TYPE_P(arguments) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "Definition arguments must be an array"); return; } PHALCON_INIT_VAR(build_arguments); array_init(build_arguments); if (!phalcon_is_iterable(arguments, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(position, ah0, hp0); PHALCON_GET_FOREACH_VALUE(argument); PHALCON_INIT_NVAR(value); PHALCON_CALL_METHOD_PARAMS_3(value, this_ptr, "_buildparameter", dependency_injector, position, argument); phalcon_array_append(&build_arguments, value, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(build_arguments); } /** * Builds a service using a complex service definition * * @param Phalcon\DiInterface $dependencyInjector * @param array $definition * @param array $parameters * @return mixed */ PHP_METHOD(Phalcon_DI_Service_Builder, build){ zval *dependency_injector, *definition, *parameters = NULL; zval *class_name, *instance = NULL, *arguments = NULL, *build_arguments = NULL; zval *param_calls = NULL, *method = NULL, *position = NULL, *exception_message = NULL; zval *method_name = NULL, *method_call = NULL, *status = NULL, *property = NULL; zval *property_name = NULL, *property_value = NULL, *value = NULL; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &dependency_injector, &definition, &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } if (Z_TYPE_P(definition) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "The service definition must be an array"); return; } /** * The class name is required */ if (!phalcon_array_isset_string(definition, SS("className"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "Invalid service definition. Missing 'className' parameter"); return; } PHALCON_OBS_VAR(class_name); phalcon_array_fetch_string(&class_name, definition, SL("className"), PH_NOISY_CC); if (Z_TYPE_P(parameters) == IS_ARRAY) { /** * Build the instance overriding the definition constructor parameters */ if (phalcon_fast_count_ev(parameters TSRMLS_CC)) { PHALCON_INIT_VAR(instance); if (phalcon_create_instance_params(instance, class_name, parameters TSRMLS_CC) == FAILURE) { return; } } else { PHALCON_INIT_NVAR(instance); if (phalcon_create_instance(instance, class_name TSRMLS_CC) == FAILURE) { return; } } } else { /** * Check if the argument has constructor arguments */ if (phalcon_array_isset_string(definition, SS("arguments"))) { PHALCON_OBS_VAR(arguments); phalcon_array_fetch_string(&arguments, definition, SL("arguments"), PH_NOISY_CC); /** * Resolve the constructor parameters */ PHALCON_INIT_VAR(build_arguments); PHALCON_CALL_METHOD_PARAMS_2(build_arguments, this_ptr, "_buildparameters", dependency_injector, arguments); /** * Create the instance based on the parameters */ PHALCON_INIT_NVAR(instance); if (phalcon_create_instance_params(instance, class_name, build_arguments TSRMLS_CC) == FAILURE) { return; } } else { PHALCON_INIT_NVAR(instance); if (phalcon_create_instance(instance, class_name TSRMLS_CC) == FAILURE) { return; } } } /** * The definition has calls? */ if (phalcon_array_isset_string(definition, SS("calls"))) { if (Z_TYPE_P(instance) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "The definition has setter injection parameters but the constructor didn't return an instance"); return; } PHALCON_OBS_VAR(param_calls); phalcon_array_fetch_string(&param_calls, definition, SL("calls"), PH_NOISY_CC); if (Z_TYPE_P(param_calls) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "Setter injection parameters must be an array"); return; } /** * The method call has parameters */ if (!phalcon_is_iterable(param_calls, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(position, ah0, hp0); PHALCON_GET_FOREACH_VALUE(method); /** * The call parameter must be an array of arrays */ if (Z_TYPE_P(method) != IS_ARRAY) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Method call must be an array on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } /** * A param 'method' is required */ if (!phalcon_array_isset_string(method, SS("method"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "The method name is required on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(method_name); phalcon_array_fetch_string(&method_name, method, SL("method"), PH_NOISY_CC); /** * Create the method call */ PHALCON_INIT_NVAR(method_call); array_init_size(method_call, 2); phalcon_array_append(&method_call, instance, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&method_call, method_name, PH_SEPARATE TSRMLS_CC); if (phalcon_array_isset_string(method, SS("arguments"))) { PHALCON_OBS_NVAR(arguments); phalcon_array_fetch_string(&arguments, method, SL("arguments"), PH_NOISY_CC); if (Z_TYPE_P(arguments) != IS_ARRAY) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Call arguments must be an array ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } if (phalcon_fast_count_ev(arguments TSRMLS_CC)) { /** * Resolve the constructor parameters */ PHALCON_INIT_NVAR(build_arguments); PHALCON_CALL_METHOD_PARAMS_2(build_arguments, this_ptr, "_buildparameters", dependency_injector, arguments); /** * Call the method on the instance */ PHALCON_INIT_NVAR(status); PHALCON_CALL_USER_FUNC_ARRAY(status, method_call, build_arguments); /** * Go to next method call */ zend_hash_move_forward_ex(ah0, &hp0); continue; } } /** * Call the method on the instance without arguments */ PHALCON_INIT_NVAR(status); PHALCON_CALL_USER_FUNC(status, method_call); zend_hash_move_forward_ex(ah0, &hp0); } } /** * The definition has properties? */ if (phalcon_array_isset_string(definition, SS("properties"))) { if (Z_TYPE_P(instance) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "The definition has properties injection parameters but the constructor didn't return an instance"); return; } PHALCON_OBS_NVAR(param_calls); phalcon_array_fetch_string(&param_calls, definition, SL("properties"), PH_NOISY_CC); if (Z_TYPE_P(param_calls) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_di_exception_ce, "Setter injection parameters must be an array"); return; } /** * The method call has parameters */ if (!phalcon_is_iterable(param_calls, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_KEY(position, ah1, hp1); PHALCON_GET_FOREACH_VALUE(property); /** * The call parameter must be an array of arrays */ if (Z_TYPE_P(property) != IS_ARRAY) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "Property must be an array on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } /** * A param 'name' is required */ if (!phalcon_array_isset_string(property, SS("name"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "The property name is required on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } /** * A param 'value' is required */ if (!phalcon_array_isset_string(property, SS("value"))) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SV(exception_message, "The property value is required on position ", position); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_di_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(property_name); phalcon_array_fetch_string(&property_name, property, SL("name"), PH_NOISY_CC); PHALCON_OBS_NVAR(property_value); phalcon_array_fetch_string(&property_value, property, SL("value"), PH_NOISY_CC); /** * Resolve the parameter */ PHALCON_INIT_NVAR(value); PHALCON_CALL_METHOD_PARAMS_3(value, this_ptr, "_buildparameter", dependency_injector, position, property_value); /** * Update the public property */ phalcon_update_property_zval_zval(instance, property_name, value TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } } RETURN_CTOR(instance); }
tmihalik/cphalcon
ext/phalcon.c
<reponame>tmihalik/cphalcon /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" zend_class_entry *phalcon_tag_ce; zend_class_entry *phalcon_acl_ce; zend_class_entry *phalcon_db_ce; zend_class_entry *phalcon_di_ce; zend_class_entry *phalcon_text_ce; zend_class_entry *phalcon_cache_backend_ce; zend_class_entry *phalcon_cache_exception_ce; zend_class_entry *phalcon_cache_frontend_data_ce; zend_class_entry *phalcon_cache_backend_mongo_ce; zend_class_entry *phalcon_cache_backend_apc_ce; zend_class_entry *phalcon_cache_frontend_none_ce; zend_class_entry *phalcon_cache_backend_file_ce; zend_class_entry *phalcon_cache_frontend_base64_ce; zend_class_entry *phalcon_cache_frontend_output_ce; zend_class_entry *phalcon_cache_backend_memcache_ce; zend_class_entry *phalcon_cache_frontendinterface_ce; zend_class_entry *phalcon_cache_backendinterface_ce; zend_class_entry *phalcon_tag_select_ce; zend_class_entry *phalcon_tag_exception_ce; zend_class_entry *phalcon_paginator_exception_ce; zend_class_entry *phalcon_paginator_adapter_model_ce; zend_class_entry *phalcon_paginator_adapterinterface_ce; zend_class_entry *phalcon_paginator_adapter_nativearray_ce; zend_class_entry *phalcon_db_index_ce; zend_class_entry *phalcon_db_dialect_ce; zend_class_entry *phalcon_db_adapter_ce; zend_class_entry *phalcon_db_profiler_ce; zend_class_entry *phalcon_db_rawvalue_ce; zend_class_entry *phalcon_db_exception_ce; zend_class_entry *phalcon_db_column_ce; zend_class_entry *phalcon_db_reference_ce; zend_class_entry *phalcon_db_adapter_pdo_ce; zend_class_entry *phalcon_db_adapterinterface_ce; zend_class_entry *phalcon_db_adapter_pdo_mysql_ce; zend_class_entry *phalcon_db_adapter_pdo_sqlite_ce; zend_class_entry *phalcon_db_adapter_pdo_postgresql_ce; zend_class_entry *phalcon_db_columninterface_ce; zend_class_entry *phalcon_db_dialect_mysql_ce; zend_class_entry *phalcon_db_dialectinterface_ce; zend_class_entry *phalcon_db_dialect_sqlite_ce; zend_class_entry *phalcon_db_dialect_postgresql_ce; zend_class_entry *phalcon_db_indexinterface_ce; zend_class_entry *phalcon_db_profiler_item_ce; zend_class_entry *phalcon_db_result_pdo_ce; zend_class_entry *phalcon_db_resultinterface_ce; zend_class_entry *phalcon_db_referenceinterface_ce; zend_class_entry *phalcon_acl_role_ce; zend_class_entry *phalcon_acl_resource_ce; zend_class_entry *phalcon_acl_adapter_ce; zend_class_entry *phalcon_acl_exception_ce; zend_class_entry *phalcon_acl_adapterinterface_ce; zend_class_entry *phalcon_acl_adapter_memory_ce; zend_class_entry *phalcon_acl_roleinterface_ce; zend_class_entry *phalcon_acl_resourceinterface_ce; zend_class_entry *phalcon_security_ce; zend_class_entry *phalcon_session_ce; zend_class_entry *phalcon_version_ce; zend_class_entry *phalcon_kernel_ce; zend_class_entry *phalcon_security_exception_ce; zend_class_entry *phalcon_session_bag_ce; zend_class_entry *phalcon_session_adapter_ce; zend_class_entry *phalcon_session_baginterface_ce; zend_class_entry *phalcon_session_exception_ce; zend_class_entry *phalcon_session_adapterinterface_ce; zend_class_entry *phalcon_session_adapter_files_ce; zend_class_entry *phalcon_filter_ce; zend_class_entry *phalcon_di_exception_ce; zend_class_entry *phalcon_di_service_ce; zend_class_entry *phalcon_di_factorydefault_ce; zend_class_entry *phalcon_di_factorydefault_cli_ce; zend_class_entry *phalcon_di_injectable_ce; zend_class_entry *phalcon_di_injectionawareinterface_ce; zend_class_entry *phalcon_di_serviceinterface_ce; zend_class_entry *phalcon_di_service_builder_ce; zend_class_entry *phalcon_diinterface_ce; zend_class_entry *phalcon_filterinterface_ce; zend_class_entry *phalcon_filter_exception_ce; zend_class_entry *phalcon_dispatcher_ce; zend_class_entry *phalcon_dispatcherinterface_ce; zend_class_entry *phalcon_cli_task_ce; zend_class_entry *phalcon_flash_ce; zend_class_entry *phalcon_flash_direct_ce; zend_class_entry *phalcon_flashinterface_ce; zend_class_entry *phalcon_flash_exception_ce; zend_class_entry *phalcon_flash_session_ce; zend_class_entry *phalcon_cli_console_ce; zend_class_entry *phalcon_cli_router_ce; zend_class_entry *phalcon_cli_dispatcher_ce; zend_class_entry *phalcon_cli_console_exception_ce; zend_class_entry *phalcon_cli_dispatcher_exception_ce; zend_class_entry *phalcon_cli_router_exception_ce; zend_class_entry *phalcon_annotations_adapter_ce; zend_class_entry *phalcon_annotations_reader_ce; zend_class_entry *phalcon_annotations_collection_ce; zend_class_entry *phalcon_annotations_annotation_ce; zend_class_entry *phalcon_annotations_exception_ce; zend_class_entry *phalcon_annotations_reflection_ce; zend_class_entry *phalcon_annotations_adapter_files_ce; zend_class_entry *phalcon_annotations_readerinterface_ce; zend_class_entry *phalcon_annotations_adapterinterface_ce; zend_class_entry *phalcon_annotations_adapter_memory_ce; zend_class_entry *phalcon_logger_ce; zend_class_entry *phalcon_config_ce; zend_class_entry *phalcon_loader_ce; zend_class_entry *phalcon_loader_exception_ce; zend_class_entry *phalcon_logger_item_ce; zend_class_entry *phalcon_logger_exception_ce; zend_class_entry *phalcon_logger_adapter_ce; zend_class_entry *phalcon_logger_formatter_ce; zend_class_entry *phalcon_logger_multiple_ce; zend_class_entry *phalcon_logger_adapter_file_ce; zend_class_entry *phalcon_logger_formatter_syslog_ce; zend_class_entry *phalcon_logger_formatter_line_ce; zend_class_entry *phalcon_logger_adapterinterface_ce; zend_class_entry *phalcon_logger_formatter_json_ce; zend_class_entry *phalcon_logger_adapter_syslog_ce; zend_class_entry *phalcon_logger_adapter_stream_ce; zend_class_entry *phalcon_logger_formatterinterface_ce; zend_class_entry *phalcon_config_exception_ce; zend_class_entry *phalcon_config_adapter_ini_ce; zend_class_entry *phalcon_translate_ce; zend_class_entry *phalcon_translate_adapter_ce; zend_class_entry *phalcon_translate_exception_ce; zend_class_entry *phalcon_translate_adapterinterface_ce; zend_class_entry *phalcon_translate_adapter_nativearray_ce; zend_class_entry *phalcon_escaper_ce; zend_class_entry *phalcon_escaperinterface_ce; zend_class_entry *phalcon_escaper_exception_ce; zend_class_entry *phalcon_http_request_ce; zend_class_entry *phalcon_http_cookie_ce; zend_class_entry *phalcon_http_response_ce; zend_class_entry *phalcon_http_request_file_ce; zend_class_entry *phalcon_http_cookie_exception_ce; zend_class_entry *phalcon_http_responseinterface_ce; zend_class_entry *phalcon_http_response_cookies_ce; zend_class_entry *phalcon_http_response_exception_ce; zend_class_entry *phalcon_http_request_exception_ce; zend_class_entry *phalcon_http_requestinterface_ce; zend_class_entry *phalcon_http_response_headers_ce; zend_class_entry *phalcon_http_request_fileinterface_ce; zend_class_entry *phalcon_http_response_headersinterface_ce; zend_class_entry *phalcon_mvc_view_ce; zend_class_entry *phalcon_mvc_url_ce; zend_class_entry *phalcon_mvc_router_ce; zend_class_entry *phalcon_mvc_micro_ce; zend_class_entry *phalcon_mvc_model_ce; zend_class_entry *phalcon_mvc_user_module_ce; zend_class_entry *phalcon_mvc_view_engine_ce; zend_class_entry *phalcon_mvc_urlinterface_ce; zend_class_entry *phalcon_mvc_collection_ce; zend_class_entry *phalcon_mvc_model_query_ce; zend_class_entry *phalcon_mvc_router_group_ce; zend_class_entry *phalcon_mvc_router_route_ce; zend_class_entry *phalcon_mvc_model_row_ce; zend_class_entry *phalcon_mvc_controller_ce; zend_class_entry *phalcon_mvc_dispatcher_ce; zend_class_entry *phalcon_mvc_application_ce; zend_class_entry *phalcon_mvc_user_plugin_ce; zend_class_entry *phalcon_mvc_application_exception_ce; zend_class_entry *phalcon_mvc_collectioninterface_ce; zend_class_entry *phalcon_mvc_collection_exception_ce; zend_class_entry *phalcon_mvc_controllerinterface_ce; zend_class_entry *phalcon_mvc_collection_manager_ce; zend_class_entry *phalcon_mvc_collection_managerinterface_ce; zend_class_entry *phalcon_mvc_dispatcher_exception_ce; zend_class_entry *phalcon_mvc_dispatcherinterface_ce; zend_class_entry *phalcon_mvc_model_metadata_ce; zend_class_entry *phalcon_mvc_micro_collection_ce; zend_class_entry *phalcon_mvc_micro_exception_ce; zend_class_entry *phalcon_mvc_model_validator_ce; zend_class_entry *phalcon_mvc_modelinterface_ce; zend_class_entry *phalcon_mvc_model_exception_ce; zend_class_entry *phalcon_mvc_model_query_lang_ce; zend_class_entry *phalcon_mvc_model_resultset_ce; zend_class_entry *phalcon_mvc_model_behavior_ce; zend_class_entry *phalcon_mvc_model_manager_ce; zend_class_entry *phalcon_mvc_model_criteria_ce; zend_class_entry *phalcon_mvc_model_relation_ce; zend_class_entry *phalcon_mvc_model_message_ce; zend_class_entry *phalcon_mvc_model_query_builder_ce; zend_class_entry *phalcon_mvc_model_metadata_files_ce; zend_class_entry *phalcon_mvc_model_queryinterface_ce; zend_class_entry *phalcon_mvc_model_query_status_ce; zend_class_entry *phalcon_mvc_model_metadata_apc_ce; zend_class_entry *phalcon_mvc_model_transaction_ce; zend_class_entry *phalcon_mvc_model_metadatainterface_ce; zend_class_entry *phalcon_mvc_model_relationinterface_ce; zend_class_entry *phalcon_mvc_model_messageinterface_ce; zend_class_entry *phalcon_mvc_model_resultset_simple_ce; zend_class_entry *phalcon_mvc_model_validator_email_ce; zend_class_entry *phalcon_mvc_model_managerinterface_ce; zend_class_entry *phalcon_mvc_model_metadata_session_ce; zend_class_entry *phalcon_mvc_model_resultinterface_ce; zend_class_entry *phalcon_mvc_model_validatorinterface_ce; zend_class_entry *phalcon_mvc_model_resultsetinterface_ce; zend_class_entry *phalcon_mvc_model_transaction_failed_ce; zend_class_entry *phalcon_mvc_model_behaviorinterface_ce; zend_class_entry *phalcon_mvc_model_criteriainterface_ce; zend_class_entry *phalcon_mvc_model_validator_regex_ce; zend_class_entry *phalcon_mvc_model_resultset_complex_ce; zend_class_entry *phalcon_mvc_model_metadata_memory_ce; zend_class_entry *phalcon_mvc_model_query_builderinterface_ce; zend_class_entry *phalcon_mvc_model_query_statusinterface_ce; zend_class_entry *phalcon_mvc_model_validator_stringlength_ce; zend_class_entry *phalcon_mvc_model_validator_numericality_ce; zend_class_entry *phalcon_mvc_model_behavior_timestampable_ce; zend_class_entry *phalcon_mvc_model_validator_exclusionin_ce; zend_class_entry *phalcon_mvc_model_transaction_exception_ce; zend_class_entry *phalcon_mvc_model_validator_inclusionin_ce; zend_class_entry *phalcon_mvc_model_behavior_softdelete_ce; zend_class_entry *phalcon_mvc_model_validator_uniqueness_ce; zend_class_entry *phalcon_mvc_model_transactioninterface_ce; zend_class_entry *phalcon_mvc_model_transaction_manager_ce; zend_class_entry *phalcon_mvc_model_validator_presenceof_ce; zend_class_entry *phalcon_mvc_model_metadata_strategy_annotations_ce; zend_class_entry *phalcon_mvc_model_transaction_managerinterface_ce; zend_class_entry *phalcon_mvc_model_metadata_strategy_introspection_ce; zend_class_entry *phalcon_mvc_moduledefinitioninterface_ce; zend_class_entry *phalcon_mvc_router_exception_ce; zend_class_entry *phalcon_mvc_routerinterface_ce; zend_class_entry *phalcon_mvc_router_annotations_ce; zend_class_entry *phalcon_mvc_router_routeinterface_ce; zend_class_entry *phalcon_mvc_user_component_ce; zend_class_entry *phalcon_mvc_url_exception_ce; zend_class_entry *phalcon_mvc_viewinterface_ce; zend_class_entry *phalcon_mvc_view_exception_ce; zend_class_entry *phalcon_mvc_view_engine_volt_ce; zend_class_entry *phalcon_mvc_view_engine_php_ce; zend_class_entry *phalcon_mvc_view_engineinterface_ce; zend_class_entry *phalcon_mvc_view_engine_volt_compiler_ce; zend_class_entry *phalcon_events_event_ce; zend_class_entry *phalcon_events_exception_ce; zend_class_entry *phalcon_events_manager_ce; zend_class_entry *phalcon_events_managerinterface_ce; zend_class_entry *phalcon_events_eventsawareinterface_ce; zend_class_entry *phalcon_exception_ce; ZEND_DECLARE_MODULE_GLOBALS(phalcon) PHP_MINIT_FUNCTION(phalcon){ if(!zend_ce_arrayaccess){ fprintf(stderr, "Phalcon Error: Interface ArrayAccess was not found"); return FAILURE; } if(!zend_ce_serializable){ fprintf(stderr, "Phalcon Error: Interface Serializable was not found"); return FAILURE; } if(!zend_ce_iterator){ fprintf(stderr, "Phalcon Error: Interface Iterator was not found"); return FAILURE; } if(!spl_ce_SeekableIterator){ fprintf(stderr, "Phalcon Error: Interface SeekableIterator was not found"); return FAILURE; } if(!spl_ce_Countable){ fprintf(stderr, "Phalcon Error: Interface Countable was not found"); return FAILURE; } /** Init globals */ ZEND_INIT_MODULE_GLOBALS(phalcon, php_phalcon_init_globals, NULL); PHALCON_INIT(Phalcon_DI_InjectionAwareInterface); PHALCON_INIT(Phalcon_Events_EventsAwareInterface); PHALCON_INIT(Phalcon_Mvc_Model_ValidatorInterface); PHALCON_INIT(Phalcon_Cache_BackendInterface); PHALCON_INIT(Phalcon_Cache_FrontendInterface); PHALCON_INIT(Phalcon_Mvc_Model_MetaDataInterface); PHALCON_INIT(Phalcon_Db_AdapterInterface); PHALCON_INIT(Phalcon_Db_DialectInterface); PHALCON_INIT(Phalcon_Logger_AdapterInterface); PHALCON_INIT(Phalcon_Logger_FormatterInterface); PHALCON_INIT(Phalcon_FlashInterface); PHALCON_INIT(Phalcon_Paginator_AdapterInterface); PHALCON_INIT(Phalcon_Mvc_Model_ResultInterface); PHALCON_INIT(Phalcon_Mvc_Model_BehaviorInterface); PHALCON_INIT(Phalcon_Mvc_Model_ResultsetInterface); PHALCON_INIT(Phalcon_Annotations_AdapterInterface); PHALCON_INIT(Phalcon_Mvc_View_EngineInterface); PHALCON_INIT(Phalcon_DispatcherInterface); PHALCON_INIT(Phalcon_Exception); PHALCON_INIT(Phalcon_DI_Injectable); PHALCON_INIT(Phalcon_Mvc_Model_RelationInterface); PHALCON_INIT(Phalcon_Mvc_Model_CriteriaInterface); PHALCON_INIT(Phalcon_Mvc_Model_MessageInterface); PHALCON_INIT(Phalcon_Mvc_Model_Transaction_ManagerInterface); PHALCON_INIT(Phalcon_Mvc_RouterInterface); PHALCON_INIT(Phalcon_Session_AdapterInterface); PHALCON_INIT(Phalcon_Mvc_Model_ManagerInterface); PHALCON_INIT(Phalcon_Mvc_ViewInterface); PHALCON_INIT(Phalcon_Mvc_Model_Query_StatusInterface); PHALCON_INIT(Phalcon_Mvc_ModelInterface); PHALCON_INIT(Phalcon_Mvc_DispatcherInterface); PHALCON_INIT(Phalcon_Mvc_UrlInterface); PHALCON_INIT(Phalcon_Mvc_CollectionInterface); PHALCON_INIT(Phalcon_DiInterface); PHALCON_INIT(Phalcon_Mvc_Model_Query_BuilderInterface); PHALCON_INIT(Phalcon_Mvc_Router_RouteInterface); PHALCON_INIT(Phalcon_Session_BagInterface); PHALCON_INIT(Phalcon_Mvc_Model_QueryInterface); PHALCON_INIT(Phalcon_Mvc_Model_TransactionInterface); PHALCON_INIT(Phalcon_Db_ColumnInterface); PHALCON_INIT(Phalcon_Http_RequestInterface); PHALCON_INIT(Phalcon_Http_ResponseInterface); PHALCON_INIT(Phalcon_Http_Request_FileInterface); PHALCON_INIT(Phalcon_Db_IndexInterface); PHALCON_INIT(Phalcon_Annotations_ReaderInterface); PHALCON_INIT(Phalcon_FilterInterface); PHALCON_INIT(Phalcon_EscaperInterface); PHALCON_INIT(Phalcon_Translate_AdapterInterface); PHALCON_INIT(Phalcon_Events_ManagerInterface); PHALCON_INIT(Phalcon_DI_ServiceInterface); PHALCON_INIT(Phalcon_Http_Response_HeadersInterface); PHALCON_INIT(Phalcon_Db_ReferenceInterface); PHALCON_INIT(Phalcon_Acl_ResourceInterface); PHALCON_INIT(Phalcon_Acl_AdapterInterface); PHALCON_INIT(Phalcon_Acl_RoleInterface); PHALCON_INIT(Phalcon_Db_Adapter); PHALCON_INIT(Phalcon_Mvc_Model_Validator); PHALCON_INIT(Phalcon_Mvc_Model_MetaData); PHALCON_INIT(Phalcon_Cache_Backend); PHALCON_INIT(Phalcon_Logger_Adapter); PHALCON_INIT(Phalcon_Logger_Formatter); PHALCON_INIT(Phalcon_Db_Dialect); PHALCON_INIT(Phalcon_Db_Adapter_Pdo); PHALCON_INIT(Phalcon_Mvc_Model_Behavior); PHALCON_INIT(Phalcon_DI); PHALCON_INIT(Phalcon_Annotations_Adapter); PHALCON_INIT(Phalcon_Flash); PHALCON_INIT(Phalcon_Mvc_View_Engine); PHALCON_INIT(Phalcon_Dispatcher); PHALCON_INIT(Phalcon_Mvc_Model_Resultset); PHALCON_INIT(Phalcon_Session_Adapter); PHALCON_INIT(Phalcon_Config); PHALCON_INIT(Phalcon_Translate_Adapter); PHALCON_INIT(Phalcon_DI_FactoryDefault); PHALCON_INIT(Phalcon_Mvc_Model_Exception); PHALCON_INIT(Phalcon_Mvc_Router); PHALCON_INIT(Phalcon_Acl_Adapter); PHALCON_INIT(Phalcon_Db); PHALCON_INIT(Phalcon_Tag); PHALCON_INIT(Phalcon_Acl); PHALCON_INIT(Phalcon_Cache_Exception); PHALCON_INIT(Phalcon_Cache_Backend_File); PHALCON_INIT(Phalcon_Cache_Backend_Apc); PHALCON_INIT(Phalcon_Cache_Backend_Mongo); PHALCON_INIT(Phalcon_Cache_Backend_Memcache); PHALCON_INIT(Phalcon_Cache_Frontend_Output); PHALCON_INIT(Phalcon_Cache_Frontend_Base64); PHALCON_INIT(Phalcon_Cache_Frontend_Data); PHALCON_INIT(Phalcon_Cache_Frontend_None); PHALCON_INIT(Phalcon_Tag_Select); PHALCON_INIT(Phalcon_Tag_Exception); PHALCON_INIT(Phalcon_Paginator_Exception); PHALCON_INIT(Phalcon_Paginator_Adapter_Model); PHALCON_INIT(Phalcon_Paginator_Adapter_NativeArray); PHALCON_INIT(Phalcon_Db_Column); PHALCON_INIT(Phalcon_Db_Index); PHALCON_INIT(Phalcon_Db_Adapter_Pdo_Mysql); PHALCON_INIT(Phalcon_Db_Adapter_Pdo_Sqlite); PHALCON_INIT(Phalcon_Db_Adapter_Pdo_Postgresql); PHALCON_INIT(Phalcon_Db_Dialect_Sqlite); PHALCON_INIT(Phalcon_Db_Dialect_Mysql); PHALCON_INIT(Phalcon_Db_Dialect_Postgresql); PHALCON_INIT(Phalcon_Db_Exception); PHALCON_INIT(Phalcon_Db_Profiler); PHALCON_INIT(Phalcon_Db_Profiler_Item); PHALCON_INIT(Phalcon_Db_RawValue); PHALCON_INIT(Phalcon_Db_Reference); PHALCON_INIT(Phalcon_Db_Result_Pdo); PHALCON_INIT(Phalcon_Db_ResultInterface); PHALCON_INIT(Phalcon_Acl_Role); PHALCON_INIT(Phalcon_Acl_Resource); PHALCON_INIT(Phalcon_Acl_Adapter_Memory); PHALCON_INIT(Phalcon_Acl_Exception); PHALCON_INIT(Phalcon_Kernel); PHALCON_INIT(Phalcon_Text); PHALCON_INIT(Phalcon_Security); PHALCON_INIT(Phalcon_Security_Exception); PHALCON_INIT(Phalcon_Version); PHALCON_INIT(Phalcon_Session); PHALCON_INIT(Phalcon_Session_Bag); PHALCON_INIT(Phalcon_Session_Exception); PHALCON_INIT(Phalcon_Session_Adapter_Files); PHALCON_INIT(Phalcon_Filter); PHALCON_INIT(Phalcon_DI_Exception); PHALCON_INIT(Phalcon_DI_FactoryDefault_CLI); PHALCON_INIT(Phalcon_DI_Service); PHALCON_INIT(Phalcon_DI_Service_Builder); PHALCON_INIT(Phalcon_Filter_Exception); PHALCON_INIT(Phalcon_Flash_Direct); PHALCON_INIT(Phalcon_Flash_Session); PHALCON_INIT(Phalcon_Flash_Exception); PHALCON_INIT(Phalcon_CLI_Task); PHALCON_INIT(Phalcon_CLI_Router); PHALCON_INIT(Phalcon_CLI_Console); PHALCON_INIT(Phalcon_CLI_Console_Exception); PHALCON_INIT(Phalcon_CLI_Dispatcher); PHALCON_INIT(Phalcon_CLI_Dispatcher_Exception); PHALCON_INIT(Phalcon_CLI_Router_Exception); PHALCON_INIT(Phalcon_Annotations_Reader); PHALCON_INIT(Phalcon_Annotations_Exception); PHALCON_INIT(Phalcon_Annotations_Reflection); PHALCON_INIT(Phalcon_Annotations_Collection); PHALCON_INIT(Phalcon_Annotations_Annotation); PHALCON_INIT(Phalcon_Annotations_Adapter_Files); PHALCON_INIT(Phalcon_Annotations_Adapter_Memory); PHALCON_INIT(Phalcon_Logger); PHALCON_INIT(Phalcon_Loader); PHALCON_INIT(Phalcon_Loader_Exception); PHALCON_INIT(Phalcon_Logger_Item); PHALCON_INIT(Phalcon_Logger_Multiple); PHALCON_INIT(Phalcon_Logger_Exception); PHALCON_INIT(Phalcon_Logger_Formatter_Line); PHALCON_INIT(Phalcon_Logger_Adapter_Syslog); PHALCON_INIT(Phalcon_Logger_Adapter_Stream); PHALCON_INIT(Phalcon_Logger_Adapter_File); PHALCON_INIT(Phalcon_Logger_Formatter_Json); PHALCON_INIT(Phalcon_Logger_Formatter_Syslog); PHALCON_INIT(Phalcon_Config_Exception); PHALCON_INIT(Phalcon_Config_Adapter_Ini); PHALCON_INIT(Phalcon_Translate); PHALCON_INIT(Phalcon_Translate_Exception); PHALCON_INIT(Phalcon_Translate_Adapter_NativeArray); PHALCON_INIT(Phalcon_Escaper); PHALCON_INIT(Phalcon_Escaper_Exception); PHALCON_INIT(Phalcon_Http_Cookie); PHALCON_INIT(Phalcon_Http_Request); PHALCON_INIT(Phalcon_Http_Response); PHALCON_INIT(Phalcon_Http_Cookie_Exception); PHALCON_INIT(Phalcon_Http_Request_File); PHALCON_INIT(Phalcon_Http_Response_Headers); PHALCON_INIT(Phalcon_Http_Response_Cookies); PHALCON_INIT(Phalcon_Http_Request_Exception); PHALCON_INIT(Phalcon_Http_Response_Exception); PHALCON_INIT(Phalcon_Mvc_Micro); PHALCON_INIT(Phalcon_Mvc_Model); PHALCON_INIT(Phalcon_Mvc_Url); PHALCON_INIT(Phalcon_Mvc_View); PHALCON_INIT(Phalcon_Mvc_Application); PHALCON_INIT(Phalcon_Mvc_Application_Exception); PHALCON_INIT(Phalcon_Mvc_Controller); PHALCON_INIT(Phalcon_Mvc_Collection); PHALCON_INIT(Phalcon_Mvc_Collection_Manager); PHALCON_INIT(Phalcon_Mvc_Collection_Exception); PHALCON_INIT(Phalcon_Mvc_Collection_ManagerInterface); PHALCON_INIT(Phalcon_Mvc_ControllerInterface); PHALCON_INIT(Phalcon_Mvc_Dispatcher); PHALCON_INIT(Phalcon_Mvc_Dispatcher_Exception); PHALCON_INIT(Phalcon_Mvc_Model_Row); PHALCON_INIT(Phalcon_Mvc_Model_Query); PHALCON_INIT(Phalcon_Mvc_Micro_Collection); PHALCON_INIT(Phalcon_Mvc_Micro_Exception); PHALCON_INIT(Phalcon_Mvc_Model_Criteria); PHALCON_INIT(Phalcon_Mvc_Model_Message); PHALCON_INIT(Phalcon_Mvc_Model_Relation); PHALCON_INIT(Phalcon_Mvc_Model_Manager); PHALCON_INIT(Phalcon_Mvc_Model_Transaction); PHALCON_INIT(Phalcon_Mvc_Model_Query_Lang); PHALCON_INIT(Phalcon_Mvc_Model_Query_Status); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Apc); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Files); PHALCON_INIT(Phalcon_Mvc_Model_Query_Builder); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Memory); PHALCON_INIT(Phalcon_Mvc_Model_Resultset_Complex); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Regex); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Email); PHALCON_INIT(Phalcon_Mvc_Model_Resultset_Simple); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Session); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Uniqueness); PHALCON_INIT(Phalcon_Mvc_Model_Transaction_Failed); PHALCON_INIT(Phalcon_Mvc_Model_Validator_PresenceOf); PHALCON_INIT(Phalcon_Mvc_Model_Transaction_Manager); PHALCON_INIT(Phalcon_Mvc_Model_Behavior_SoftDelete); PHALCON_INIT(Phalcon_Mvc_Model_Behavior_Timestampable); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Strategy_Annotations); PHALCON_INIT(Phalcon_Mvc_Model_MetaData_Strategy_Introspection); PHALCON_INIT(Phalcon_Mvc_Model_Transaction_Exception); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Numericality); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Exclusionin); PHALCON_INIT(Phalcon_Mvc_Model_Validator_StringLength); PHALCON_INIT(Phalcon_Mvc_Model_Validator_Inclusionin); PHALCON_INIT(Phalcon_Mvc_ModuleDefinitionInterface); PHALCON_INIT(Phalcon_Mvc_Router_Group); PHALCON_INIT(Phalcon_Mvc_Router_Route); PHALCON_INIT(Phalcon_Mvc_Router_Exception); PHALCON_INIT(Phalcon_Mvc_Router_Annotations); PHALCON_INIT(Phalcon_Mvc_User_Plugin); PHALCON_INIT(Phalcon_Mvc_User_Module); PHALCON_INIT(Phalcon_Mvc_Url_Exception); PHALCON_INIT(Phalcon_Mvc_User_Component); PHALCON_INIT(Phalcon_Mvc_View_Exception); PHALCON_INIT(Phalcon_Mvc_View_Engine_Php); PHALCON_INIT(Phalcon_Mvc_View_Engine_Volt); PHALCON_INIT(Phalcon_Mvc_View_Engine_Volt_Compiler); PHALCON_INIT(Phalcon_Events_Event); PHALCON_INIT(Phalcon_Events_Manager); PHALCON_INIT(Phalcon_Events_Exception); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(phalcon){ if (PHALCON_GLOBAL(active_memory) != NULL) { phalcon_clean_shutdown_stack(TSRMLS_C); } if (PHALCON_GLOBAL(function_cache) != NULL) { zend_hash_destroy(PHALCON_GLOBAL(function_cache)); FREE_HASHTABLE(PHALCON_GLOBAL(function_cache)); PHALCON_GLOBAL(function_cache) = NULL; } return SUCCESS; } PHP_RINIT_FUNCTION(phalcon){ php_phalcon_init_globals(PHALCON_VGLOBAL TSRMLS_CC); return SUCCESS; } PHP_RSHUTDOWN_FUNCTION(phalcon){ if (PHALCON_GLOBAL(active_memory) != NULL) { phalcon_clean_shutdown_stack(TSRMLS_C); } if (PHALCON_GLOBAL(function_cache) != NULL) { zend_hash_destroy(PHALCON_GLOBAL(function_cache)); FREE_HASHTABLE(PHALCON_GLOBAL(function_cache)); PHALCON_GLOBAL(function_cache) = NULL; } return SUCCESS; } zend_module_entry phalcon_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif PHP_PHALCON_EXTNAME, NULL, PHP_MINIT(phalcon), PHP_MSHUTDOWN(phalcon), PHP_RINIT(phalcon), PHP_RSHUTDOWN(phalcon), NULL, #if ZEND_MODULE_API_NO >= 20010901 PHP_PHALCON_VERSION, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_PHALCON ZEND_GET_MODULE(phalcon) #endif
tmihalik/cphalcon
ext/kernel/operators.c
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "ext/standard/php_string.h" #include "php_phalcon.h" #include "kernel/main.h" #include "kernel/memory.h" #include "Zend/zend_operators.h" void phalcon_make_printable_zval(zval *expr, zval *expr_copy, int *use_copy){ zend_make_printable_zval(expr, expr_copy, use_copy); if (use_copy) { Z_SET_REFCOUNT_P(expr_copy, 1); Z_UNSET_ISREF_P(expr_copy); } } /** * Performs logical AND function operator */ int phalcon_and_function(zval *result, zval *left, zval *right){ int istrue = zend_is_true(left); if (istrue) { istrue = zend_is_true(right); } ZVAL_BOOL(result, istrue); return SUCCESS; } /** * Appends the content of the right operator to the left operator */ void phalcon_concat_self(zval **left, zval *right TSRMLS_DC){ zval left_copy, right_copy; uint length; int use_copy_left = 0, use_copy_right = 0; if (Z_TYPE_P(right) != IS_STRING) { phalcon_make_printable_zval(right, &right_copy, &use_copy_right); if (use_copy_right) { PHALCON_CPY_WRT_CTOR(right, (&right_copy)); } } if (Z_TYPE_PP(left) == IS_NULL) { Z_STRVAL_PP(left) = emalloc(Z_STRLEN_P(right)+1); memcpy(Z_STRVAL_PP(left), Z_STRVAL_P(right), Z_STRLEN_P(right)); Z_STRVAL_PP(left)[Z_STRLEN_P(right)] = 0; Z_STRLEN_PP(left) = Z_STRLEN_P(right); Z_TYPE_PP(left) = IS_STRING; if (use_copy_right) { zval_dtor(&right_copy); } return; } if (Z_TYPE_PP(left) != IS_STRING) { phalcon_make_printable_zval(*left, &left_copy, &use_copy_left); if (use_copy_left) { PHALCON_CPY_WRT_CTOR(*left, (&left_copy)); } } length = Z_STRLEN_PP(left) + Z_STRLEN_P(right); Z_STRVAL_PP(left) = erealloc(Z_STRVAL_PP(left), length+1); memcpy(Z_STRVAL_PP(left) + Z_STRLEN_PP(left), Z_STRVAL_P(right), Z_STRLEN_P(right)); Z_STRVAL_PP(left)[length] = 0; Z_STRLEN_PP(left) = length; Z_TYPE_PP(left) = IS_STRING; if (use_copy_left) { zval_dtor(&left_copy); } if (use_copy_right) { zval_dtor(&right_copy); } } /** * Appends the content of the right operator to the left operator */ void phalcon_concat_self_str(zval **left, char *right, int right_length TSRMLS_DC){ zval left_copy; uint length; int use_copy = 0; if (Z_TYPE_PP(left) == IS_NULL) { Z_STRVAL_PP(left) = emalloc(right_length + 1); memcpy(Z_STRVAL_PP(left), right, right_length); Z_STRVAL_PP(left)[right_length] = 0; Z_STRLEN_PP(left) = right_length; Z_TYPE_PP(left) = IS_STRING; return; } if (Z_TYPE_PP(left) != IS_STRING) { phalcon_make_printable_zval(*left, &left_copy, &use_copy); if (use_copy) { PHALCON_CPY_WRT_CTOR(*left, (&left_copy)); } } length = Z_STRLEN_PP(left) + right_length; Z_STRVAL_PP(left) = erealloc(Z_STRVAL_PP(left), length + 1); memcpy(Z_STRVAL_PP(left) + Z_STRLEN_PP(left), right, right_length); Z_STRVAL_PP(left)[length] = 0; Z_STRLEN_PP(left) = length; Z_TYPE_PP(left) = IS_STRING; if (use_copy) { zval_dtor(&left_copy); } } /** * Natural compare with string operadus on right */ int phalcon_compare_strict_string(zval *op1, char *op2, int op2_length){ switch (Z_TYPE_P(op1)) { case IS_STRING: if (!Z_STRLEN_P(op1) && !op2_length) { return 1; } if (Z_STRLEN_P(op1) != op2_length) { return 0; } return zend_binary_strcmp(Z_STRVAL_P(op1), Z_STRLEN_P(op1), op2, op2_length)==0; case IS_NULL: return zend_binary_strcmp("", 0, op2, op2_length)==0; case IS_BOOL: if (!Z_BVAL_P(op1)) { return zend_binary_strcmp("0", strlen("0"), op2, op2_length)==0; } else { return zend_binary_strcmp("1", strlen("1"), op2, op2_length)==0; } } return 0; } /** * Natural compare with long operadus on right */ int phalcon_compare_strict_long(zval *op1, long op2 TSRMLS_DC){ zval *op2_tmp, *result; int bool_result; switch (Z_TYPE_P(op1)) { case IS_LONG: return Z_LVAL_P(op1) == op2; case IS_DOUBLE: return Z_LVAL_P(op1) == (double) op2; case IS_NULL: return 0 == op2; case IS_BOOL: if (Z_BVAL_P(op1)) { return 0 == op2; } else { return 1 == op2; } default: ALLOC_INIT_ZVAL(result); ALLOC_INIT_ZVAL(op2_tmp); ZVAL_LONG(op2_tmp, op2); is_equal_function(result, op1, op2_tmp TSRMLS_CC); bool_result = Z_BVAL_P(result); zval_ptr_dtor(&result); zval_ptr_dtor(&op2_tmp); return bool_result; } return 0; } /** * Natural is smaller compare with long operadus on right */ int phalcon_is_smaller_strict_long(zval *op1, long op2 TSRMLS_DC){ zval *op2_tmp, *result; int bool_result; switch (Z_TYPE_P(op1)) { case IS_LONG: return Z_LVAL_P(op1) < op2; case IS_DOUBLE: return Z_LVAL_P(op1) < (double) op2; case IS_NULL: return 0 < op2; case IS_BOOL: if (Z_BVAL_P(op1)) { return 0 < op2; } else { return 1 < op2; } default: ALLOC_INIT_ZVAL(result); ALLOC_INIT_ZVAL(op2_tmp); ZVAL_LONG(op2_tmp, op2); is_smaller_function(result, op1, op2_tmp TSRMLS_CC); bool_result = Z_BVAL_P(result); zval_ptr_dtor(&result); zval_ptr_dtor(&op2_tmp); return bool_result; } } /** * Natural is smaller or equal compare with long operadus on right */ int phalcon_is_smaller_or_equal_strict_long(zval *op1, long op2 TSRMLS_DC){ zval *op2_tmp, *result; int bool_result; switch (Z_TYPE_P(op1)) { case IS_LONG: return Z_LVAL_P(op1) <= op2; case IS_DOUBLE: return Z_DVAL_P(op1) <= (double) op2; case IS_NULL: return 0 < op2; case IS_BOOL: if (Z_BVAL_P(op1)) { return 0 <= op2; } else { return 1 <= op2; } default: ALLOC_INIT_ZVAL(result); ALLOC_INIT_ZVAL(op2_tmp); ZVAL_LONG(op2_tmp, op2); is_smaller_or_equal_function(result, op1, op2_tmp TSRMLS_CC); bool_result = Z_BVAL_P(result); zval_ptr_dtor(&result); zval_ptr_dtor(&op2_tmp); return bool_result; } } /** * Do add function keeping ref_count and is_ref */ int phalcon_add_function(zval *result, zval *op1, zval *op2 TSRMLS_DC){ int status; int ref_count = Z_REFCOUNT_P(result); int is_ref = Z_ISREF_P(result); status = add_function(result, op1, op2 TSRMLS_CC); Z_SET_REFCOUNT_P(result, ref_count); Z_SET_ISREF_TO_P(result, is_ref); return status; } /** * Cast variables converting they to other types */ void phalcon_cast(zval *result, zval *var, zend_uint type){ ZVAL_ZVAL(result, var, 1, 0); switch (type) { case IS_STRING: convert_to_string(result); break; case IS_LONG: convert_to_long(result); break; /*case IS_BOOL: convert_to_bool(result); break;*/ case IS_ARRAY: if (Z_TYPE_P(result) != IS_ARRAY) { convert_to_array(result); } break; } } /** * Returns the long value of a zval */ long phalcon_get_intval(zval *op) { int type; long long_value; double double_value; switch (Z_TYPE_P(op)) { case IS_LONG: return Z_LVAL_P(op); case IS_BOOL: return Z_BVAL_P(op); case IS_DOUBLE: return (long) Z_DVAL_P(op); case IS_STRING: if((type = is_numeric_string(Z_STRVAL_P(op), Z_STRLEN_P(op), &long_value, &double_value, 0))){ if (type == IS_LONG) { return long_value; } else { if (type == IS_DOUBLE) { return double_value; } else { return 0; } } } } return 0; } /** * Returns the long value of a zval */ int phalcon_is_numeric(zval *op) { int type; switch (Z_TYPE_P(op)) { case IS_LONG: return 1; case IS_BOOL: return 0; case IS_DOUBLE: return 1; case IS_STRING: if((type = is_numeric_string(Z_STRVAL_P(op), Z_STRLEN_P(op), NULL, NULL, 0))){ if (type == IS_LONG || type == IS_DOUBLE) { return 1; } } } return 0; } /** * Check if two zvals are equal */ int phalcon_is_equal(zval *op1, zval *op2 TSRMLS_DC) { zval result; is_equal_function(&result, op1, op2 TSRMLS_CC); return Z_BVAL(result); } /** * Check if two zvals are identical */ int phalcon_is_identical(zval *op1, zval *op2 TSRMLS_DC) { zval result; is_identical_function(&result, op1, op2 TSRMLS_CC); return Z_BVAL(result); }
tmihalik/cphalcon
ext/mvc/model/resultset/complex.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/operators.h" #include "kernel/fcall.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/string.h" #include "kernel/exception.h" /** * Phalcon\Mvc\Model\Resultset\Complex * * Complex resultsets may include complete objects and scalar values. * This class builds every complex row as the're required */ /** * Phalcon\Mvc\Model\Resultset\Complex initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Resultset_Complex){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\Model\\Resultset, Complex, mvc_model_resultset_complex, "phalcon\\mvc\\model\\resultset", phalcon_mvc_model_resultset_complex_method_entry, 0); zend_declare_property_null(phalcon_mvc_model_resultset_complex_ce, SL("_columnTypes"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_model_resultset_complex_ce TSRMLS_CC, 1, phalcon_mvc_model_resultsetinterface_ce); return SUCCESS; } /** * Phalcon\Mvc\Model\Resultset\Complex constructor * * @param array $columnsTypes * @param Phalcon\Db\ResultInterface $result * @param Phalcon\Cache\BackendInterface $cache */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Complex, __construct){ zval *columns_types, *result, *cache = NULL, *fetch_assoc; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &columns_types, &result, &cache) == FAILURE) { RETURN_MM_NULL(); } if (!cache) { PHALCON_INIT_VAR(cache); } phalcon_update_property_zval(this_ptr, SL("_columnTypes"), columns_types TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_result"), result TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_cache"), cache TSRMLS_CC); phalcon_update_property_long(this_ptr, SL("_type"), 1 TSRMLS_CC); if (PHALCON_IS_NOT_FALSE(result)) { PHALCON_INIT_VAR(fetch_assoc); ZVAL_LONG(fetch_assoc, 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(result, "setfetchmode", fetch_assoc); } PHALCON_MM_RESTORE(); } /** * Check whether internal resource has rows to fetch * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Complex, valid){ zval *type = NULL, *result, *row = NULL, *rows, *hydrate_mode, *underscore; zval *empty_str, *active_row = NULL, *columns_types; zval *column = NULL, *alias = NULL, *source = NULL, *attributes = NULL, *column_map = NULL; zval *row_model = NULL, *attribute = NULL, *column_alias = NULL, *column_value = NULL; zval *instance = NULL, *value = NULL, *sql_alias = NULL, *n_alias = NULL; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(type); phalcon_read_property(&type, this_ptr, SL("_type"), PH_NOISY_CC); if (zend_is_true(type)) { /** * The result is bigger than 32 rows so it's retrieved one by one */ PHALCON_OBS_VAR(result); phalcon_read_property(&result, this_ptr, SL("_result"), PH_NOISY_CC); if (PHALCON_IS_NOT_FALSE(result)) { PHALCON_INIT_VAR(row); PHALCON_CALL_METHOD_PARAMS_1(row, result, "fetch", result); } else { PHALCON_INIT_NVAR(row); ZVAL_BOOL(row, 0); } } else { /** * The full rows are dumped in this_ptr->rows */ PHALCON_OBS_VAR(rows); phalcon_read_property(&rows, this_ptr, SL("_rows"), PH_NOISY_CC); if (Z_TYPE_P(rows) == IS_ARRAY) { PHALCON_INIT_NVAR(row); phalcon_array_get_current(row, rows TSRMLS_CC); if (Z_TYPE_P(row) == IS_OBJECT) { phalcon_array_next(rows); } } else { PHALCON_INIT_NVAR(row); ZVAL_BOOL(row, 0); } } /** * Valid records are arrays */ if (Z_TYPE_P(row) == IS_ARRAY || Z_TYPE_P(row) == IS_OBJECT) { /** * The result type=1 so we need to build every row */ if (zend_is_true(type)) { /** * Get current hydration mode */ PHALCON_OBS_VAR(hydrate_mode); phalcon_read_property(&hydrate_mode, this_ptr, SL("_hydrateMode"), PH_NOISY_CC); PHALCON_INIT_VAR(underscore); ZVAL_STRING(underscore, "_", 1); PHALCON_INIT_VAR(empty_str); ZVAL_STRING(empty_str, "", 1); /** * Each row in a complex result is a Phalcon\Mvc\Model\Row instance */ switch (phalcon_get_intval(hydrate_mode)) { case 0: PHALCON_INIT_VAR(active_row); object_init_ex(active_row, phalcon_mvc_model_row_ce); break; case 1: PHALCON_INIT_NVAR(active_row); array_init(active_row); break; case 2: PHALCON_INIT_NVAR(active_row); object_init(active_row); break; } /** * Create every record according to the column types */ PHALCON_OBS_VAR(columns_types); phalcon_read_property(&columns_types, this_ptr, SL("_columnTypes"), PH_NOISY_CC); if (!phalcon_is_iterable(columns_types, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(alias, ah0, hp0); PHALCON_GET_FOREACH_VALUE(column); PHALCON_OBS_NVAR(type); phalcon_array_fetch_string(&type, column, SL("type"), PH_NOISY_CC); if (PHALCON_IS_STRING(type, "object")) { /** * Object columns are assigned column by column */ PHALCON_OBS_NVAR(source); phalcon_array_fetch_string(&source, column, SL("column"), PH_NOISY_CC); PHALCON_OBS_NVAR(attributes); phalcon_array_fetch_string(&attributes, column, SL("attributes"), PH_NOISY_CC); PHALCON_OBS_NVAR(column_map); phalcon_array_fetch_string(&column_map, column, SL("columnMap"), PH_NOISY_CC); /** * Assign the values from the _source_attribute notation to its real column name */ PHALCON_INIT_NVAR(row_model); array_init(row_model); if (!phalcon_is_iterable(attributes, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); /** * Columns are supposed to be in the form _table_field */ PHALCON_INIT_NVAR(column_alias); PHALCON_CONCAT_VVVV(column_alias, underscore, source, underscore, attribute); PHALCON_OBS_NVAR(column_value); phalcon_array_fetch(&column_value, row, column_alias, PH_NOISY_CC); phalcon_array_update_zval(&row_model, attribute, &column_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } /** * Generate the column value according to the hydration type */ switch (phalcon_get_intval(hydrate_mode)) { case 0: PHALCON_OBS_NVAR(instance); phalcon_array_fetch_string(&instance, column, SL("instance"), PH_NOISY_CC); /** * Assign the values to the attributes using a column map */ PHALCON_INIT_NVAR(value); PHALCON_CALL_STATIC_PARAMS_3(value, "phalcon\\mvc\\model", "cloneresultmap", instance, row_model, column_map); break; default: /** * Other kinds of hydrations */ PHALCON_INIT_NVAR(value); PHALCON_CALL_STATIC_PARAMS_3(value, "phalcon\\mvc\\model", "cloneresultmaphydrate", row_model, column_map, hydrate_mode); break; } /** * The complete object is assigned to an attribute with the name of the alias or * the model name */ PHALCON_OBS_NVAR(attribute); phalcon_array_fetch_string(&attribute, column, SL("balias"), PH_NOISY_CC); } else { /** * Scalar columns are simply assigned to the result object */ if (phalcon_array_isset_string(column, SS("sqlAlias"))) { PHALCON_OBS_NVAR(sql_alias); phalcon_array_fetch_string(&sql_alias, column, SL("sqlAlias"), PH_NOISY_CC); PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, row, sql_alias, PH_NOISY_CC); } else { PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, row, alias, PH_NOISY_CC); } /** * If a 'balias' is defined is not an unnamed scalar */ if (phalcon_array_isset_string(column, SS("balias"))) { PHALCON_CPY_WRT(attribute, alias); } else { PHALCON_INIT_NVAR(n_alias); phalcon_fast_str_replace(n_alias, underscore, empty_str, alias TSRMLS_CC); PHALCON_CPY_WRT(attribute, n_alias); } } /** * Assign the instance according to the hydration type */ switch (phalcon_get_intval(hydrate_mode)) { case 1: phalcon_array_update_zval(&active_row, attribute, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); break; default: phalcon_update_property_zval_zval(active_row, attribute, value TSRMLS_CC); break; } zend_hash_move_forward_ex(ah0, &hp0); } /** * Store the generated row in this_ptr->activeRow to be retrieved by 'current' */ phalcon_update_property_zval(this_ptr, SL("_activeRow"), active_row TSRMLS_CC); } else { /** * The row is already built so we just assign it to the activeRow */ phalcon_update_property_zval(this_ptr, SL("_activeRow"), row TSRMLS_CC); } RETURN_MM_TRUE; } /** * There are no results to retrieve so we update this_ptr->activeRow as false */ phalcon_update_property_bool(this_ptr, SL("_activeRow"), 0 TSRMLS_CC); RETURN_MM_FALSE; } /** * Returns a complete resultset as an array, if the resultset has a big number of rows * it could consume more memory than currently it does. * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Complex, toArray){ zval *records, *valid = NULL, *current = NULL; zval *r0 = NULL; PHALCON_MM_GROW(); PHALCON_INIT_VAR(records); array_init(records); PHALCON_CALL_METHOD_NORETURN(this_ptr, "rewind"); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, this_ptr, "valid"); PHALCON_CPY_WRT(valid, r0); if (PHALCON_IS_NOT_FALSE(valid)) { } else { break; } PHALCON_INIT_NVAR(current); PHALCON_CALL_METHOD(current, this_ptr, "current"); phalcon_array_append(&records, current, PH_SEPARATE TSRMLS_CC); PHALCON_CALL_METHOD_NORETURN(this_ptr, "next"); } RETURN_CTOR(records); } /** * Serializing a resultset will dump all related rows into a big array * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Complex, serialize){ zval *records, *cache, *column_types, *hydrate_mode; zval *data, *serialized; PHALCON_MM_GROW(); /** * Obtain the records as an array */ PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD(records, this_ptr, "toarray"); PHALCON_OBS_VAR(cache); phalcon_read_property(&cache, this_ptr, SL("_cache"), PH_NOISY_CC); PHALCON_OBS_VAR(column_types); phalcon_read_property(&column_types, this_ptr, SL("_columnTypes"), PH_NOISY_CC); PHALCON_OBS_VAR(hydrate_mode); phalcon_read_property(&hydrate_mode, this_ptr, SL("_hydrateMode"), PH_NOISY_CC); PHALCON_INIT_VAR(data); array_init_size(data, 4); phalcon_array_update_string(&data, SL("cache"), &cache, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("rows"), &records, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("columnTypes"), &column_types, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("hydrateMode"), &hydrate_mode, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(serialized); PHALCON_CALL_FUNC_PARAMS_1(serialized, "serialize", data); RETURN_CCTOR(serialized); } /** * Unserializing a resultset will allow to only works on the rows present in the saved state * * @param string $data */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Complex, unserialize){ zval *data, *resultset, *rows, *cache, *column_types; zval *hydrate_mode; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } phalcon_update_property_long(this_ptr, SL("_type"), 0 TSRMLS_CC); PHALCON_INIT_VAR(resultset); PHALCON_CALL_FUNC_PARAMS_1(resultset, "unserialize", data); if (Z_TYPE_P(resultset) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid serialization data"); return; } PHALCON_OBS_VAR(rows); phalcon_array_fetch_string(&rows, resultset, SL("rows"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_rows"), rows TSRMLS_CC); PHALCON_OBS_VAR(cache); phalcon_array_fetch_string(&cache, resultset, SL("cache"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_cache"), cache TSRMLS_CC); PHALCON_OBS_VAR(column_types); phalcon_array_fetch_string(&column_types, resultset, SL("columnTypes"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_columnTypes"), column_types TSRMLS_CC); PHALCON_OBS_VAR(hydrate_mode); phalcon_array_fetch_string(&hydrate_mode, resultset, SL("hydrateMode"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_hydrateMode"), hydrate_mode TSRMLS_CC); PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/mvc/model.c
<reponame>tmihalik/cphalcon /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/string.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/operators.h" #include "kernel/file.h" /** * Phalcon\Mvc\Model * * <p>Phalcon\Mvc\Model connects business objects and database tables to create * a persistable domain model where logic and data are presented in one wrapping. * It‘s an implementation of the object-relational mapping (ORM).</p> * * <p>A model represents the information (data) of the application and the rules to manipulate that data. * Models are primarily used for managing the rules of interaction with a corresponding database table. * In most cases, each table in your database will correspond to one model in your application. * The bulk of your application’s business logic will be concentrated in the models.</p> * * <p>Phalcon\Mvc\Model is the first ORM written in C-language for PHP, giving to developers high performance * when interacting with databases while is also easy to use.</p> * * <code> * * $robot = new Robots(); * $robot->type = 'mechanical' * $robot->name = '<NAME>'; * $robot->year = 1952; * if ($robot->save() == false) { * echo "Umh, We can store robots: "; * foreach ($robot->getMessages() as $message) { * echo $message; * } * } else { * echo "Great, a new robot was saved successfully!"; * } * </code> * */ /** * Phalcon\Mvc\Model initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc, Model, mvc_model, phalcon_mvc_model_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_declare_property_null(phalcon_mvc_model_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_modelsManager"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_modelsMetaData"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_schema"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_source"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_errorMessages"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_model_ce, SL("_operationMade"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_model_ce, SL("_dirtyState"), 1, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_connection"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_uniqueKey"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_uniqueParams"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_uniqueTypes"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_skipped"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_ce, SL("_related"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("OP_NONE"), 0 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("OP_CREATE"), 1 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("OP_UPDATE"), 2 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("OP_DELETE"), 3 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("DIRTY_STATE_PERSISTENT"), 0 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("DIRTY_STATE_TRANSIENT"), 1 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_model_ce, SL("DIRTY_STATE_DETACHED"), 2 TSRMLS_CC); zend_class_implements(phalcon_mvc_model_ce TSRMLS_CC, 4, phalcon_mvc_modelinterface_ce, phalcon_mvc_model_resultinterface_ce, phalcon_di_injectionawareinterface_ce, zend_ce_serializable); return SUCCESS; } /** * Phalcon\Mvc\Model constructor * * @param Phalcon\DiInterface $dependencyInjector * @param Phalcon\Mvc\Model\ManagerInterface $modelsManager */ PHP_METHOD(Phalcon_Mvc_Model, __construct){ zval *dependency_injector = NULL, *models_manager = NULL; zval *service_name; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &dependency_injector, &models_manager) == FAILURE) { RETURN_MM_NULL(); } if (!dependency_injector) { PHALCON_INIT_VAR(dependency_injector); } else { PHALCON_SEPARATE_PARAM(dependency_injector); } if (!models_manager) { PHALCON_INIT_VAR(models_manager); } else { PHALCON_SEPARATE_PARAM(models_manager); } /** * We use a default DI if the user doesn't define one */ if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_INIT_NVAR(dependency_injector); PHALCON_CALL_STATIC(dependency_injector, "phalcon\\di", "getdefault"); } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ORM"); return; } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); /** * Inject the manager service from the DI */ if (Z_TYPE_P(models_manager) != IS_OBJECT) { PHALCON_INIT_VAR(service_name); ZVAL_STRING(service_name, "modelsManager", 1); PHALCON_INIT_NVAR(models_manager); PHALCON_CALL_METHOD_PARAMS_1(models_manager, dependency_injector, "getshared", service_name); if (Z_TYPE_P(models_manager) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The injected service 'modelsManager' is not valid"); return; } } /** * Update the models-manager */ phalcon_update_property_zval(this_ptr, SL("_modelsManager"), models_manager TSRMLS_CC); /** * The manager always initializes the object */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(models_manager, "initialize", this_ptr); PHALCON_MM_RESTORE(); } /** * Sets the dependency injection container * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_Model, setDI){ zval *dependency_injector; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); } /** * Returns the dependency injection container * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Mvc_Model, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Sets a custom events manager * * @param Phalcon\Events\ManagerInterface $eventsManager */ PHP_METHOD(Phalcon_Mvc_Model, setEventsManager){ zval *events_manager, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &events_manager) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(models_manager, "setcustomeventsmanager", this_ptr, events_manager); PHALCON_MM_RESTORE(); } /** * Returns the custom events manager * * @return Phalcon\Events\ManagerInterface */ PHP_METHOD(Phalcon_Mvc_Model, getEventsManager){ zval *models_manager, *events_manager; PHALCON_MM_GROW(); PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(events_manager); PHALCON_CALL_METHOD_PARAMS_1(events_manager, models_manager, "getcustomeventsmanager", this_ptr); RETURN_CCTOR(events_manager); } /** * Returns the models meta-data service related to the entity instance * * @return Phalcon\Mvc\Model\MetaDataInterface */ PHP_METHOD(Phalcon_Mvc_Model, getModelsMetaData){ zval *meta_data = NULL, *dependency_injector, *service; PHALCON_MM_GROW(); PHALCON_OBS_VAR(meta_data); phalcon_read_property(&meta_data, this_ptr, SL("_modelsMetaData"), PH_NOISY_CC); if (Z_TYPE_P(meta_data) != IS_OBJECT) { /** * Check if the DI is valid */ PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ORM"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "modelsMetadata", 1); /** * Obtain the models-metadata service from the DI */ PHALCON_INIT_NVAR(meta_data); PHALCON_CALL_METHOD_PARAMS_1(meta_data, dependency_injector, "getshared", service); if (Z_TYPE_P(meta_data) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The injected service 'modelsMetadata' is not valid"); return; } /** * Update the models-metada property */ phalcon_update_property_zval(this_ptr, SL("_modelsMetaData"), meta_data TSRMLS_CC); } RETURN_CCTOR(meta_data); } /** * Returns the models manager related to the entity instance * * @return Phalcon\Mvc\Model\ManagerInterface */ PHP_METHOD(Phalcon_Mvc_Model, getModelsManager){ RETURN_MEMBER(this_ptr, "_modelsManager"); } /** * Sets a transaction related to the Model instance * *<code> *use Phalcon\Mvc\Model\Transaction\Manager as TxManager; *use Phalcon\Mvc\Model\Transaction\Failed as TxFailed; * *try { * * $txManager = new TxManager(); * * $transaction = $txManager->get(); * * $robot = new Robots(); * $robot->setTransaction($transaction); * $robot->name = 'WALL·E'; * $robot->created_at = date('Y-m-d'); * if ($robot->save() == false) { * $transaction->rollback("Can't save robot"); * } * * $robotPart = new RobotParts(); * $robotPart->setTransaction($transaction); * $robotPart->type = 'head'; * if ($robotPart->save() == false) { * $transaction->rollback("Robot part cannot be saved"); * } * * $transaction->commit(); * *} catch (TxFailed $e) { * echo 'Failed, reason: ', $e->getMessage(); *} * *</code> * * @param Phalcon\Mvc\Model\TransactionInterface $transaction * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, setTransaction){ zval *transaction, *connection; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &transaction) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(transaction) == IS_OBJECT) { PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, transaction, "getconnection"); phalcon_update_property_zval(this_ptr, SL("_connection"), connection TSRMLS_CC); RETURN_THIS(); } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Transaction should be an object"); return; } /** * Sets table name which model should be mapped (deprecated) * * @param string $source * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, setSource){ zval *source; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &source) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_source"), source TSRMLS_CC); RETURN_THISW(); } /** * Returns table name mapped in the model * * @return string */ PHP_METHOD(Phalcon_Mvc_Model, getSource){ zval *source = NULL, *class_name; PHALCON_MM_GROW(); PHALCON_OBS_VAR(source); phalcon_read_property(&source, this_ptr, SL("_source"), PH_NOISY_CC); if (!zend_is_true(source)) { PHALCON_INIT_VAR(class_name); phalcon_get_class_ns(class_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_NVAR(source); phalcon_uncamelize(source, class_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_source"), source TSRMLS_CC); } RETURN_CCTOR(source); } /** * Sets schema name where table mapped is located (deprecated) * * @param string $schema * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, setSchema){ zval *schema; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &schema) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_schema"), schema TSRMLS_CC); RETURN_THISW(); } /** * Returns schema name where table mapped is located * * @return string */ PHP_METHOD(Phalcon_Mvc_Model, getSchema){ RETURN_MEMBER(this_ptr, "_schema"); } /** * Sets the DependencyInjection connection service name * * @param string $connectionService * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, setConnectionService){ zval *connection_service, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &connection_service) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(models_manager, "setconnectionservice", this_ptr, connection_service); RETURN_THIS(); } /** * Returns the DependencyInjection connection service name related to the model * * @return string */ PHP_METHOD(Phalcon_Mvc_Model, getConnectionService){ zval *models_manager, *connection_service; PHALCON_MM_GROW(); PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(connection_service); PHALCON_CALL_METHOD_PARAMS_1(connection_service, models_manager, "getconnectionservice", this_ptr); RETURN_CCTOR(connection_service); } /** * Sets the dirty state of the object using one of the DIRTY_STATE_* constants * * @param int $dirtyState * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, setDirtyState){ zval *dirty_state; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dirty_state) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_dirtyState"), dirty_state TSRMLS_CC); RETURN_THISW(); } /** * Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not * * @return int */ PHP_METHOD(Phalcon_Mvc_Model, getDirtyState){ RETURN_MEMBER(this_ptr, "_dirtyState"); } /** * Gets the internal database connection * * @return Phalcon\Db\AdapterInterface */ PHP_METHOD(Phalcon_Mvc_Model, getConnection){ zval *connection = NULL, *models_manager; PHALCON_MM_GROW(); PHALCON_OBS_VAR(connection); phalcon_read_property(&connection, this_ptr, SL("_connection"), PH_NOISY_CC); if (Z_TYPE_P(connection) != IS_OBJECT) { PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_NVAR(connection); PHALCON_CALL_METHOD_PARAMS_1(connection, models_manager, "getconnection", this_ptr); phalcon_update_property_zval(this_ptr, SL("_connection"), connection TSRMLS_CC); } RETURN_CCTOR(connection); } /** * Assigns values to a model from an array returning a new model. * *<code> *$robot = \Phalcon\Mvc\Model::cloneResultMap(new Robots(), array( * 'type' => 'mechanical', * 'name' => '<NAME>', * 'year' => 1952 *)); *</code> * * @param Phalcon\Mvc\Model $base * @param array $data * @param array $columnMap * @param int $dirtyState * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, cloneResultMap){ zval *base, *data, *column_map, *dirty_state = NULL, *object; zval *value = NULL, *key = NULL, *attribute = NULL, *exception_message = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &base, &data, &column_map, &dirty_state) == FAILURE) { RETURN_MM_NULL(); } if (!dirty_state) { PHALCON_INIT_VAR(dirty_state); ZVAL_LONG(dirty_state, 0); } if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data to dump in the object must be an Array"); return; } PHALCON_INIT_VAR(object); if (phalcon_clone(object, base TSRMLS_CC) == FAILURE) { return; } /** * Change the dirty state to persistent */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(object, "setdirtystate", dirty_state); if (!phalcon_is_iterable(data, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (Z_TYPE_P(key) == IS_STRING) { /** * Only string keys in the data are valid */ if (Z_TYPE_P(column_map) == IS_ARRAY) { /** * Every field must be part of the column map */ if (phalcon_array_isset(column_map, key)) { PHALCON_OBS_NVAR(attribute); phalcon_array_fetch(&attribute, column_map, key, PH_NOISY_CC); phalcon_update_property_zval_zval(object, attribute, value TSRMLS_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column \"", key, "\" doesn't make part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { phalcon_update_property_zval_zval(object, key, value TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CCTOR(object); } /** * Returns an hydrated result based on the data and the column map * * @param array $data * @param array $columnMap * @param int $hydrationMode * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, cloneResultMapHydrate){ zval *data, *column_map, *hydration_mode, *hydrate = NULL; zval *value = NULL, *key = NULL, *exception_message = NULL, *attribute = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &data, &column_map, &hydration_mode) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data to hidrate must be an Array"); return; } /** * If there is no column map and the hydration mode is arrays return the data as it * is */ if (Z_TYPE_P(column_map) != IS_ARRAY) { if (PHALCON_IS_LONG(hydration_mode, 1)) { RETURN_CCTOR(data); } } /** * Create the destination object according to the hydration mode */ if (PHALCON_IS_LONG(hydration_mode, 1)) { PHALCON_INIT_VAR(hydrate); array_init(hydrate); } else { PHALCON_INIT_NVAR(hydrate); object_init(hydrate); } if (!phalcon_is_iterable(data, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (Z_TYPE_P(key) == IS_STRING) { if (Z_TYPE_P(column_map) == IS_ARRAY) { /** * Every field must be part of the column map */ if (!phalcon_array_isset(column_map, key)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column \"", key, "\" doesn't make part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(attribute); phalcon_array_fetch(&attribute, column_map, key, PH_NOISY_CC); if (PHALCON_IS_LONG(hydration_mode, 1)) { phalcon_array_update_zval(&hydrate, attribute, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_update_property_zval_zval(hydrate, attribute, value TSRMLS_CC); } } else { if (PHALCON_IS_LONG(hydration_mode, 1)) { phalcon_array_update_zval(&hydrate, key, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_update_property_zval_zval(hydrate, key, value TSRMLS_CC); } } } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CCTOR(hydrate); } /** * Assigns values to a model from an array returning a new model * *<code> *$robot = Phalcon\Mvc\Model::cloneResult(new Robots(), array( * 'type' => 'mechanical', * 'name' => '<NAME>', * 'year' => 1952 *)); *</code> * * @param Phalcon\Mvc\Model $base * @param array $data * @param int $dirtyState * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, cloneResult){ zval *base, *data, *dirty_state = NULL, *object, *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &base, &data, &dirty_state) == FAILURE) { RETURN_MM_NULL(); } if (!dirty_state) { PHALCON_INIT_VAR(dirty_state); ZVAL_LONG(dirty_state, 0); } if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data to dump in the object must be an Array"); return; } PHALCON_INIT_VAR(object); if (phalcon_clone(object, base TSRMLS_CC) == FAILURE) { return; } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(object, "setdirtystate", dirty_state); if (!phalcon_is_iterable(data, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (Z_TYPE_P(key) == IS_STRING) { phalcon_update_property_zval_zval(object, key, value TSRMLS_CC); } else { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid key in array data provided to dumpResult()"); return; } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CCTOR(object); } /** * Allows to query a set of records that match the specified conditions * * <code> * * //How many robots are there? * $robots = Robots::find(); * echo "There are ", count($robots), "\n"; * * //How many mechanical robots are there? * $robots = Robots::find("type='mechanical'"); * echo "There are ", count($robots), "\n"; * * //Get and print virtual robots ordered by name * $robots = Robots::find(array("type='virtual'", "order" => "name")); * foreach ($robots as $robot) { * echo $robot->name, "\n"; * } * * //Get first 100 virtual robots ordered by name * $robots = Robots::find(array("type='virtual'", "order" => "name", "limit" => 100)); * foreach ($robots as $robot) { * echo $robot->name, "\n"; * } * </code> * * @param array $parameters * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model, find){ zval *parameters = NULL, *model_name, *params = NULL, *builder; zval *query, *bind_params = NULL, *bind_types = NULL, *cache; zval *resultset, *hydration; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(model_name); phalcon_get_called_class(model_name TSRMLS_CC); if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_INIT_VAR(params); array_init(params); if (Z_TYPE_P(parameters) != IS_NULL) { phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC); } } else { PHALCON_CPY_WRT(params, parameters); } /** * Builds a query with the passed parameters */ PHALCON_INIT_VAR(builder); object_init_ex(builder, phalcon_mvc_model_query_builder_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "__construct", params); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "from", model_name); PHALCON_INIT_VAR(query); PHALCON_CALL_METHOD(query, builder, "getquery"); /** * Check for bind parameters */ PHALCON_INIT_VAR(bind_params); PHALCON_INIT_VAR(bind_types); if (phalcon_array_isset_string(params, SS("bind"))) { PHALCON_OBS_NVAR(bind_params); phalcon_array_fetch_string(&bind_params, params, SL("bind"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("bindTypes"))) { PHALCON_OBS_NVAR(bind_types); phalcon_array_fetch_string(&bind_types, params, SL("bindTypes"), PH_NOISY_CC); } } /** * Pass the cache options to the query */ if (phalcon_array_isset_string(params, SS("cache"))) { PHALCON_OBS_VAR(cache); phalcon_array_fetch_string(&cache, params, SL("cache"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "cache", cache); } /** * Execute the query passing the bind-params and casting-types */ PHALCON_INIT_VAR(resultset); PHALCON_CALL_METHOD_PARAMS_2(resultset, query, "execute", bind_params, bind_types); /** * Define an hydration mode */ if (Z_TYPE_P(resultset) == IS_OBJECT) { if (phalcon_array_isset_string(params, SS("hydration"))) { PHALCON_OBS_VAR(hydration); phalcon_array_fetch_string(&hydration, params, SL("hydration"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(resultset, "sethydratemode", hydration); } } RETURN_CCTOR(resultset); } /** * Allows to query the first record that match the specified conditions * * <code> * * //What's the first robot in robots table? * $robot = Robots::findFirst(); * echo "The robot name is ", $robot->name; * * //What's the first mechanical robot in robots table? * $robot = Robots::findFirst("type='mechanical'"); * echo "The first mechanical robot name is ", $robot->name; * * //Get first virtual robot ordered by name * $robot = Robots::findFirst(array("type='virtual'", "order" => "name")); * echo "The first virtual robot name is ", $robot->name; * * </code> * * @param array $parameters * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Model, findFirst){ zval *parameters = NULL, *model_name, *params = NULL, *builder; zval *one, *query, *bind_params = NULL, *bind_types = NULL, *cache; zval *unique, *resultset; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(model_name); phalcon_get_called_class(model_name TSRMLS_CC); if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_INIT_VAR(params); array_init(params); if (Z_TYPE_P(parameters) != IS_NULL) { phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC); } } else { PHALCON_CPY_WRT(params, parameters); } /** * Builds a query with the passed parameters */ PHALCON_INIT_VAR(builder); object_init_ex(builder, phalcon_mvc_model_query_builder_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "__construct", params); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "from", model_name); /** * We only want the first record */ PHALCON_INIT_VAR(one); ZVAL_LONG(one, 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "limit", one); PHALCON_INIT_VAR(query); PHALCON_CALL_METHOD(query, builder, "getquery"); /** * Check for bind parameters */ PHALCON_INIT_VAR(bind_params); PHALCON_INIT_VAR(bind_types); if (phalcon_array_isset_string(params, SS("bind"))) { PHALCON_OBS_NVAR(bind_params); phalcon_array_fetch_string(&bind_params, params, SL("bind"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("bindTypes"))) { PHALCON_OBS_NVAR(bind_types); phalcon_array_fetch_string(&bind_types, params, SL("bindTypes"), PH_NOISY_CC); } } /** * Pass the cache options to the query */ if (phalcon_array_isset_string(params, SS("cache"))) { PHALCON_OBS_VAR(cache); phalcon_array_fetch_string(&cache, params, SL("cache"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "cache", cache); } PHALCON_INIT_VAR(unique); ZVAL_BOOL(unique, 1); /** * Return only the first row */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "setuniquerow", unique); /** * Execute the query passing the bind-params and casting-types */ PHALCON_INIT_VAR(resultset); PHALCON_CALL_METHOD_PARAMS_2(resultset, query, "execute", bind_params, bind_types); RETURN_CCTOR(resultset); } /** * Create a criteria for a specific model * * @param Phalcon\DiInterface $dependencyInjector * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model, query){ zval *dependency_injector = NULL, *model_name, *criteria; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &dependency_injector) == FAILURE) { RETURN_MM_NULL(); } if (!dependency_injector) { PHALCON_INIT_VAR(dependency_injector); } else { PHALCON_SEPARATE_PARAM(dependency_injector); } PHALCON_INIT_VAR(model_name); phalcon_get_called_class(model_name TSRMLS_CC); /** * Use the global dependency injector if there is no one defined */ if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_INIT_NVAR(dependency_injector); PHALCON_CALL_STATIC(dependency_injector, "phalcon\\di", "getdefault"); } PHALCON_INIT_VAR(criteria); object_init_ex(criteria, phalcon_mvc_model_criteria_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(criteria, "setdi", dependency_injector); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(criteria, "setmodelname", model_name); RETURN_CTOR(criteria); } /** * Checks if the current record already exists or not * * @param Phalcon\Mvc\Model\MetadataInterface $metaData * @param Phalcon\Db\AdapterInterface $connection * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _exists){ zval *meta_data, *connection, *table = NULL, *unique_params = NULL; zval *unique_types = NULL, *unique_key = NULL, *primary_keys; zval *bind_data_types, *number_primary, *column_map = NULL; zval *null_value, *number_empty, *where_pk, *field = NULL; zval *attribute_field = NULL, *exception_message = NULL; zval *value = NULL, *escaped_field = NULL, *pk_condition = NULL, *type = NULL; zval *join_where, *dirty_state, *schema, *source; zval *escaped_table, *null_mode, *select, *num; zval *row_count; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &meta_data, &connection, &table) == FAILURE) { RETURN_MM_NULL(); } if (!table) { PHALCON_INIT_VAR(table); } else { PHALCON_SEPARATE_PARAM(table); } PHALCON_INIT_VAR(unique_params); PHALCON_INIT_VAR(unique_types); /** * Builds a unique primary key condition */ PHALCON_OBS_VAR(unique_key); phalcon_read_property(&unique_key, this_ptr, SL("_uniqueKey"), PH_NOISY_CC); if (Z_TYPE_P(unique_key) == IS_NULL) { PHALCON_INIT_VAR(primary_keys); PHALCON_CALL_METHOD_PARAMS_1(primary_keys, meta_data, "getprimarykeyattributes", this_ptr); PHALCON_INIT_VAR(bind_data_types); PHALCON_CALL_METHOD_PARAMS_1(bind_data_types, meta_data, "getbindtypes", this_ptr); PHALCON_INIT_VAR(number_primary); phalcon_fast_count(number_primary, primary_keys TSRMLS_CC); if (!zend_is_true(number_primary)) { RETURN_MM_FALSE; } /** * Check if column renaming is globally activated */ if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(number_empty); ZVAL_LONG(number_empty, 0); PHALCON_INIT_VAR(where_pk); array_init(where_pk); array_init(unique_params); array_init(unique_types); /** * We need to create a primary key based on the current data */ if (!phalcon_is_iterable(primary_keys, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, field); } /** * If the primary key attribute is set append it to the conditions */ if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); /** * We count how many fields are empty, if all fields are empy we don't perform an * 'exist' check */ if (PHALCON_IS_EMPTY(value)) { PHALCON_SEPARATE(number_empty); increment_function(number_empty); } phalcon_array_append(&unique_params, value, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&unique_params, null_value, PH_SEPARATE TSRMLS_CC); PHALCON_SEPARATE(number_empty); increment_function(number_empty); } PHALCON_INIT_NVAR(escaped_field); PHALCON_CALL_METHOD_PARAMS_1(escaped_field, connection, "escapeidentifier", field); PHALCON_INIT_NVAR(pk_condition); PHALCON_CONCAT_VS(pk_condition, escaped_field, " = ?"); if (!phalcon_array_isset(bind_data_types, field)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the table columns"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(type); phalcon_array_fetch(&type, bind_data_types, field, PH_NOISY_CC); phalcon_array_append(&unique_types, type, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&where_pk, pk_condition, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } if (!PHALCON_IS_EQUAL(number_primary, number_empty)) { PHALCON_INIT_VAR(join_where); phalcon_fast_join_str(join_where, SL(" AND "), where_pk TSRMLS_CC); /** * The unique key is composed of 3 parts _uniqueKey, uniqueParams, uniqueTypes */ phalcon_update_property_zval(this_ptr, SL("_uniqueKey"), join_where TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_uniqueParams"), unique_params TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_uniqueTypes"), unique_types TSRMLS_CC); PHALCON_CPY_WRT(unique_key, join_where); } else { RETURN_MM_FALSE; } } /** * If we already know if the record exists we don't check it */ PHALCON_OBS_VAR(dirty_state); phalcon_read_property(&dirty_state, this_ptr, SL("_dirtyState"), PH_NOISY_CC); if (!zend_is_true(dirty_state)) { RETURN_MM_TRUE; } if (Z_TYPE_P(unique_key) == IS_NULL) { PHALCON_OBS_NVAR(unique_key); phalcon_read_property(&unique_key, this_ptr, SL("_uniqueKey"), PH_NOISY_CC); } if (Z_TYPE_P(unique_params) == IS_NULL) { PHALCON_OBS_NVAR(unique_params); phalcon_read_property(&unique_params, this_ptr, SL("_uniqueParams"), PH_NOISY_CC); } if (Z_TYPE_P(unique_types) == IS_NULL) { PHALCON_OBS_NVAR(unique_types); phalcon_read_property(&unique_types, this_ptr, SL("_uniqueTypes"), PH_NOISY_CC); } PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, this_ptr, "getschema"); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); if (zend_is_true(schema)) { PHALCON_INIT_NVAR(table); array_init_size(table, 2); phalcon_array_append(&table, schema, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&table, source, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(table, source); } PHALCON_INIT_VAR(escaped_table); PHALCON_CALL_METHOD_PARAMS_1(escaped_table, connection, "escapeidentifier", table); PHALCON_INIT_VAR(null_mode); /** * Here we use a single COUNT(*) without PHQL to make the execution faster */ PHALCON_INIT_VAR(select); PHALCON_CONCAT_SVSV(select, "SELECT COUNT(*) AS rowcount FROM ", escaped_table, " WHERE ", unique_key); PHALCON_INIT_VAR(num); PHALCON_CALL_METHOD_PARAMS_4(num, connection, "fetchone", select, null_mode, unique_params, unique_types); PHALCON_OBS_VAR(row_count); phalcon_array_fetch_string(&row_count, num, SL("rowcount"), PH_NOISY_CC); if (zend_is_true(row_count)) { phalcon_update_property_long(this_ptr, SL("_dirtyState"), 0 TSRMLS_CC); RETURN_MM_TRUE; } else { phalcon_update_property_long(this_ptr, SL("_dirtyState"), 1 TSRMLS_CC); } RETURN_MM_FALSE; } /** * Generate a PHQL SELECT statement for an aggregate * * @param string $function * @param string $alias * @param array $parameters * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model, _groupResult){ zval *function, *alias, *parameters, *params = NULL, *group_column = NULL; zval *distinct_column, *columns = NULL, *group_columns; zval *model_name, *builder, *query, *bind_params = NULL; zval *bind_types = NULL, *resultset, *cache, *number_rows; zval *first_row, *value; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &function, &alias, &parameters) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(parameters) != IS_ARRAY) { if (Z_TYPE_P(parameters) != IS_NULL) { PHALCON_INIT_VAR(params); array_init_size(params, 1); phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC); } else { PHALCON_INIT_NVAR(params); array_init(params); } } else { PHALCON_CPY_WRT(params, parameters); } if (phalcon_array_isset_string(params, SS("column"))) { PHALCON_OBS_VAR(group_column); phalcon_array_fetch_string(&group_column, params, SL("column"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(group_column); ZVAL_STRING(group_column, "*", 1); } /** * Builds the columns to query according to the received parameters */ if (phalcon_array_isset_string(params, SS("distinct"))) { PHALCON_OBS_VAR(distinct_column); phalcon_array_fetch_string(&distinct_column, params, SL("distinct"), PH_NOISY_CC); PHALCON_INIT_VAR(columns); PHALCON_CONCAT_VSVSV(columns, function, "(DISTINCT ", distinct_column, ") AS ", alias); } else { if (phalcon_array_isset_string(params, SS("group"))) { PHALCON_OBS_VAR(group_columns); phalcon_array_fetch_string(&group_columns, params, SL("group"), PH_NOISY_CC); PHALCON_INIT_NVAR(columns); PHALCON_CONCAT_VSVSVSV(columns, group_columns, ", ", function, "(", group_column, ") AS ", alias); } else { PHALCON_INIT_NVAR(columns); PHALCON_CONCAT_VSVSV(columns, function, "(", group_column, ") AS ", alias); } } PHALCON_INIT_VAR(model_name); phalcon_get_called_class(model_name TSRMLS_CC); /** * Builds a query with the passed parameters */ PHALCON_INIT_VAR(builder); object_init_ex(builder, phalcon_mvc_model_query_builder_ce); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "__construct", params); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "columns", columns); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(builder, "from", model_name); PHALCON_INIT_VAR(query); PHALCON_CALL_METHOD(query, builder, "getquery"); /** * Check for bind parameters */ PHALCON_INIT_VAR(bind_params); PHALCON_INIT_VAR(bind_types); if (phalcon_array_isset_string(params, SS("bind"))) { PHALCON_OBS_NVAR(bind_params); phalcon_array_fetch_string(&bind_params, params, SL("bind"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("bindTypes"))) { PHALCON_OBS_NVAR(bind_types); phalcon_array_fetch_string(&bind_types, params, SL("bindTypes"), PH_NOISY_CC); } } /** * Execute the query */ PHALCON_INIT_VAR(resultset); PHALCON_CALL_METHOD_PARAMS_2(resultset, query, "execute", bind_params, bind_types); /** * Pass the cache options to the query */ if (phalcon_array_isset_string(params, SS("cache"))) { PHALCON_OBS_VAR(cache); phalcon_array_fetch_string(&cache, params, SL("cache"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(query, "cache", cache); } /** * Return the full resultset if the query is grouped */ if (phalcon_array_isset_string(params, SS("group"))) { RETURN_CCTOR(resultset); } /** * Return only the value in the first result */ PHALCON_INIT_VAR(number_rows); phalcon_fast_count(number_rows, resultset TSRMLS_CC); PHALCON_INIT_VAR(first_row); PHALCON_CALL_METHOD(first_row, resultset, "getfirst"); PHALCON_OBS_VAR(value); phalcon_read_property_zval(&value, first_row, alias, PH_NOISY_CC); RETURN_CCTOR(value); } /** * Allows to count how many records match the specified conditions * * <code> * * //How many robots are there? * $number = Robots::count(); * echo "There are ", $number, "\n"; * * //How many mechanical robots are there? * $number = Robots::count("type='mechanical'"); * echo "There are ", $number, " mechanical robots\n"; * * </code> * * @param array $parameters * @return int */ PHP_METHOD(Phalcon_Mvc_Model, count){ zval *parameters = NULL, *function, *alias, *group; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(function); ZVAL_STRING(function, "COUNT", 1); PHALCON_INIT_VAR(alias); ZVAL_STRING(alias, "rowcount", 1); PHALCON_INIT_VAR(group); PHALCON_CALL_SELF_PARAMS_3(group, this_ptr, "_groupresult", function, alias, parameters); RETURN_CCTOR(group); } /** * Allows to calculate a summatory on a column that match the specified conditions * * <code> * * //How much are all robots? * $sum = Robots::sum(array('column' => 'price')); * echo "The total price of robots is ", $sum, "\n"; * * //How much are mechanical robots? * $sum = Robots::sum(array("type='mechanical'", 'column' => 'price')); * echo "The total price of mechanical robots is ", $sum, "\n"; * * </code> * * @param array $parameters * @return double */ PHP_METHOD(Phalcon_Mvc_Model, sum){ zval *parameters = NULL, *function, *alias, *group; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(function); ZVAL_STRING(function, "SUM", 1); PHALCON_INIT_VAR(alias); ZVAL_STRING(alias, "sumatory", 1); PHALCON_INIT_VAR(group); PHALCON_CALL_SELF_PARAMS_3(group, this_ptr, "_groupresult", function, alias, parameters); RETURN_CCTOR(group); } /** * Allows to get the maximum value of a column that match the specified conditions * * <code> * * //What is the maximum robot id? * $id = Robots::maximum(array('column' => 'id')); * echo "The maximum robot id is: ", $id, "\n"; * * //What is the maximum id of mechanical robots? * $sum = Robots::maximum(array("type='mechanical'", 'column' => 'id')); * echo "The maximum robot id of mechanical robots is ", $id, "\n"; * * </code> * * @param array $parameters * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, maximum){ zval *parameters = NULL, *function, *alias, *group; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(function); ZVAL_STRING(function, "MAX", 1); PHALCON_INIT_VAR(alias); ZVAL_STRING(alias, "maximum", 1); PHALCON_INIT_VAR(group); PHALCON_CALL_SELF_PARAMS_3(group, this_ptr, "_groupresult", function, alias, parameters); RETURN_CCTOR(group); } /** * Allows to get the minimum value of a column that match the specified conditions * * <code> * * //What is the minimum robot id? * $id = Robots::minimum(array('column' => 'id')); * echo "The minimum robot id is: ", $id; * * //What is the minimum id of mechanical robots? * $sum = Robots::minimum(array("type='mechanical'", 'column' => 'id')); * echo "The minimum robot id of mechanical robots is ", $id; * * </code> * * @param array $parameters * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, minimum){ zval *parameters = NULL, *function, *alias, *group; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(function); ZVAL_STRING(function, "MIN", 1); PHALCON_INIT_VAR(alias); ZVAL_STRING(alias, "minimum", 1); PHALCON_INIT_VAR(group); PHALCON_CALL_SELF_PARAMS_3(group, this_ptr, "_groupresult", function, alias, parameters); RETURN_CCTOR(group); } /** * Allows to calculate the average value on a column matching the specified conditions * * <code> * * //What's the average price of robots? * $average = Robots::average(array('column' => 'price')); * echo "The average price is ", $average, "\n"; * * //What's the average price of mechanical robots? * $average = Robots::average(array("type='mechanical'", 'column' => 'price')); * echo "The average price of mechanical robots is ", $average, "\n"; * * </code> * * @param array $parameters * @return double */ PHP_METHOD(Phalcon_Mvc_Model, average){ zval *parameters = NULL, *function, *alias, *group; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } PHALCON_INIT_VAR(function); ZVAL_STRING(function, "AVG", 1); PHALCON_INIT_VAR(alias); ZVAL_STRING(alias, "average", 1); PHALCON_INIT_VAR(group); PHALCON_CALL_SELF_PARAMS_3(group, this_ptr, "_groupresult", function, alias, parameters); RETURN_CCTOR(group); } /** * Fires an event, implicitly calls behaviors and listeners in the events manager are notified * * @param string $eventName * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, fireEvent){ zval *event_name, *models_manager, *success; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &event_name) == FAILURE) { RETURN_MM_NULL(); } /** * Check if there is a method with the same name of the event */ if (phalcon_method_exists(this_ptr, event_name TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD_NORETURN(this_ptr, Z_STRVAL_P(event_name)); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Send a notification to the events manager */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_2(success, models_manager, "notifyevent", event_name, this_ptr); RETURN_CCTOR(success); } /** * Fires an event, implicitly calls behaviors and listeners in the events manager are notified * This method stops if one of the callbacks/listeners returns boolean false * * @param string $eventName * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, fireEventCancel){ zval *event_name, *status = NULL, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &event_name) == FAILURE) { RETURN_MM_NULL(); } /** * Check if there is a method with the same name of the event */ if (phalcon_method_exists(this_ptr, event_name TSRMLS_CC) == SUCCESS) { PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD(status, this_ptr, Z_STRVAL_P(event_name)); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Send a notification to the events manager */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, models_manager, "notifyevent", event_name, this_ptr); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } RETURN_MM_TRUE; } /** * Cancel the current operation * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _cancelOperation){ zval *operation_made, *event_name = NULL; PHALCON_MM_GROW(); PHALCON_OBS_VAR(operation_made); phalcon_read_property(&operation_made, this_ptr, SL("_operationMade"), PH_NOISY_CC); if (PHALCON_IS_LONG(operation_made, 3)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "notDeleted", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "notSaved", 1); } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_MM_RESTORE(); } /** * Appends a customized message on the validation process * * <code> * use \Phalcon\Mvc\Model\Message as Message; * * class Robots extends Phalcon\Mvc\Model * { * * public function beforeSave() * { * if (this->name == 'Peter') { * $message = new Message("Sorry, but a robot cannot be named Peter"); * $this->appendMessage($message); * } * } * } * </code> * * @param Phalcon\Mvc\Model\MessageInterface $message */ PHP_METHOD(Phalcon_Mvc_Model, appendMessage){ zval *message, *type, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &message) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(message) != IS_OBJECT) { PHALCON_INIT_VAR(type); PHALCON_CALL_FUNC_PARAMS_1(type, "gettype", message); PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Invalid message format '", type, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_update_property_array_append(this_ptr, SL("_errorMessages"), message TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Executes validators on every validation call * *<code> *use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; * *class Subscriptors extends Phalcon\Mvc\Model *{ * * public function validation() * { * $this->validate(new ExclusionIn(array( * 'field' => 'status', * 'domain' => array('A', 'I') * ))); * if ($this->validationHasFailed() == true) { * return false; * } * } * *} *</code> * * @param object $validator */ PHP_METHOD(Phalcon_Mvc_Model, validate){ zval *validator, *status, *messages, *message = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &validator) == FAILURE) { RETURN_MM_NULL(); } /** * Valid validators are objects */ if (Z_TYPE_P(validator) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Validator must be an Object"); return; } /** * Call the validation, if it returns false we append the messages to the current * object */ PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, validator, "validate", this_ptr); if (PHALCON_IS_FALSE(status)) { PHALCON_INIT_VAR(messages); PHALCON_CALL_METHOD(messages, validator, "getmessages"); if (!phalcon_is_iterable(messages, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(message); phalcon_update_property_array_append(this_ptr, SL("_errorMessages"), message TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } } PHALCON_MM_RESTORE(); } /** * Check whether validation process has generated any messages * *<code> *use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; * *class Subscriptors extends Phalcon\Mvc\Model *{ * * public function validation() * { * $this->validate(new ExclusionIn(array( * 'field' => 'status', * 'domain' => array('A', 'I') * ))); * if ($this->validationHasFailed() == true) { * return false; * } * } * *} *</code> * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, validationHasFailed){ zval *error_messages; PHALCON_MM_GROW(); PHALCON_OBS_VAR(error_messages); phalcon_read_property(&error_messages, this_ptr, SL("_errorMessages"), PH_NOISY_CC); if (Z_TYPE_P(error_messages) == IS_ARRAY) { if (phalcon_fast_count_ev(error_messages TSRMLS_CC)) { RETURN_MM_TRUE; } } RETURN_MM_FALSE; } /** * Returns all the validation messages * *<code> * $robot = new Robots(); * $robot->type = 'mechanical'; * $robot->name = '<NAME>'; * $robot->year = 1952; * if ($robot->save() == false) { * echo "Umh, We can't store robots right now "; * foreach ($robot->getMessages() as $message) { * echo $message; * } * } else { * echo "Great, a new robot was saved successfully!"; * } * </code> * * @return Phalcon\Mvc\Model\MessageInterface[] */ PHP_METHOD(Phalcon_Mvc_Model, getMessages){ RETURN_MEMBER(this_ptr, "_errorMessages"); } /** * Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _checkForeignKeys){ zval *manager, *belongs_to, *relation = NULL, *foreign_key = NULL; zval *relation_class = NULL, *referenced_model = NULL, *conditions = NULL; zval *bind_params = NULL, *fields = NULL, *referenced_fields = NULL; zval *field = NULL, *position = NULL, *value = NULL, *referenced_field = NULL; zval *condition = NULL, *extra_conditions = NULL, *join_conditions = NULL; zval *parameters = NULL, *rowcount = NULL, *user_message = NULL, *joined_fields = NULL; zval *type = NULL, *message = NULL, *event_name; zend_bool error; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); /** * Get the models manager */ PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * We check if some of the belongsTo relations act as virtual foreign key */ PHALCON_INIT_VAR(belongs_to); PHALCON_CALL_METHOD_PARAMS_1(belongs_to, manager, "getbelongsto", this_ptr); if (phalcon_fast_count_ev(belongs_to TSRMLS_CC)) { error = 0; if (!phalcon_is_iterable(belongs_to, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(relation); PHALCON_INIT_NVAR(foreign_key); PHALCON_CALL_METHOD(foreign_key, relation, "getforeignkey"); if (PHALCON_IS_NOT_FALSE(foreign_key)) { PHALCON_INIT_NVAR(relation_class); PHALCON_CALL_METHOD(relation_class, relation, "getreferencedmodel"); /** * Load the referenced model if needed */ PHALCON_INIT_NVAR(referenced_model); PHALCON_CALL_METHOD_PARAMS_1(referenced_model, manager, "load", relation_class); /** * Since relations can have multiple columns or a single one, we need to build a * condition for each of these cases */ PHALCON_INIT_NVAR(conditions); array_init(conditions); PHALCON_INIT_NVAR(bind_params); array_init(bind_params); PHALCON_INIT_NVAR(fields); PHALCON_CALL_METHOD(fields, relation, "getfields"); PHALCON_INIT_NVAR(referenced_fields); PHALCON_CALL_METHOD(referenced_fields, relation, "getreferencedfields"); if (Z_TYPE_P(fields) == IS_ARRAY) { /** * Create a compound condition */ if (!phalcon_is_iterable(fields, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_KEY(position, ah1, hp1); PHALCON_GET_FOREACH_VALUE(field); if (phalcon_isset_property_zval(this_ptr, field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(value); } PHALCON_OBS_NVAR(referenced_field); phalcon_array_fetch(&referenced_field, referenced_fields, position, PH_NOISY_CC); PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VSV(condition, referenced_field, " = ?", position); phalcon_array_append(&conditions, condition, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_params, value, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } } else { /** * Create a simple condition */ if (phalcon_isset_property_zval(this_ptr, fields TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, fields, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(value); } PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VS(condition, referenced_fields, " = ?0"); phalcon_array_append(&conditions, condition, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_params, value, PH_SEPARATE TSRMLS_CC); } /** * Check if the virtual foreign key has extra conditions */ if (phalcon_array_isset_string(foreign_key, SS("conditions"))) { PHALCON_OBS_NVAR(extra_conditions); phalcon_array_fetch_string(&extra_conditions, foreign_key, SL("conditions"), PH_NOISY_CC); phalcon_array_append(&conditions, extra_conditions, PH_SEPARATE TSRMLS_CC); } /** * We don't trust the actual values in the object and pass the values using bound * parameters */ PHALCON_INIT_NVAR(join_conditions); phalcon_fast_join_str(join_conditions, SL(" AND "), conditions TSRMLS_CC); PHALCON_INIT_NVAR(parameters); array_init_size(parameters, 2); phalcon_array_append(&parameters, join_conditions, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&parameters, SL("bind"), &bind_params, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Let's make the checking */ PHALCON_INIT_NVAR(rowcount); PHALCON_CALL_METHOD_PARAMS_1(rowcount, referenced_model, "count", parameters); if (!zend_is_true(rowcount)) { /** * Get the user message or produce a new one */ if (phalcon_array_isset_string(foreign_key, SS("message"))) { PHALCON_OBS_NVAR(user_message); phalcon_array_fetch_string(&user_message, foreign_key, SL("message"), PH_NOISY_CC); } else { if (Z_TYPE_P(fields) == IS_ARRAY) { PHALCON_INIT_NVAR(joined_fields); phalcon_fast_join_str(joined_fields, SL(", "), fields TSRMLS_CC); PHALCON_INIT_NVAR(user_message); PHALCON_CONCAT_SVS(user_message, "Value of fields \"", joined_fields, "\" does not exist on referenced table"); } else { PHALCON_INIT_NVAR(user_message); PHALCON_CONCAT_SVS(user_message, "Value of field \"", fields, "\" does not exist on referenced table"); } } /** * Create a message */ PHALCON_INIT_NVAR(type); ZVAL_STRING(type, "ConstraintViolation", 1); PHALCON_INIT_NVAR(message); object_init_ex(message, phalcon_mvc_model_message_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(message, "__construct", user_message, fields, type); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "appendmessage", message); error = 1; break; } } zend_hash_move_forward_ex(ah0, &hp0); } /** * Call 'onValidationFails' if the validation fails */ if (error) { if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "onValidationFails", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_CALL_METHOD_NORETURN(this_ptr, "_canceloperation"); } RETURN_MM_FALSE; } } RETURN_MM_TRUE; } /** * Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys when deleting records * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _checkForeignKeysReverse){ zval *manager, *relations, *error = NULL, *relation = NULL, *foreign_key = NULL; zval *relation_class = NULL, *referenced_model = NULL, *fields = NULL; zval *referenced_fields = NULL, *conditions = NULL, *bind_params = NULL; zval *field = NULL, *position = NULL, *value = NULL, *referenced_field = NULL; zval *condition = NULL, *extra_conditions = NULL, *join_conditions = NULL; zval *parameters = NULL, *rowcount = NULL, *user_message = NULL, *type = NULL; zval *message = NULL, *event_name; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); /** * Get the models manager */ PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * We check if some of the hasOne/hasMany relations is a foreign key */ PHALCON_INIT_VAR(relations); PHALCON_CALL_METHOD_PARAMS_1(relations, manager, "gethasoneandhasmany", this_ptr); if (phalcon_fast_count_ev(relations TSRMLS_CC)) { PHALCON_INIT_VAR(error); ZVAL_BOOL(error, 0); if (!phalcon_is_iterable(relations, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(relation); /** * Check if the relation has a virtual foreign key */ PHALCON_INIT_NVAR(foreign_key); PHALCON_CALL_METHOD(foreign_key, relation, "getforeignkey"); if (PHALCON_IS_NOT_FALSE(foreign_key)) { PHALCON_INIT_NVAR(relation_class); PHALCON_CALL_METHOD(relation_class, relation, "getreferencedmodel"); /** * Load a plain instance from the models manager */ PHALCON_INIT_NVAR(referenced_model); PHALCON_CALL_METHOD_PARAMS_1(referenced_model, manager, "load", relation_class); PHALCON_INIT_NVAR(fields); PHALCON_CALL_METHOD(fields, relation, "getfields"); PHALCON_INIT_NVAR(referenced_fields); PHALCON_CALL_METHOD(referenced_fields, relation, "getreferencedfields"); /** * Create the checking conditions. A relation can has many fields or a single one */ PHALCON_INIT_NVAR(conditions); array_init(conditions); PHALCON_INIT_NVAR(bind_params); array_init(bind_params); if (Z_TYPE_P(fields) == IS_ARRAY) { if (!phalcon_is_iterable(fields, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_KEY(position, ah1, hp1); PHALCON_GET_FOREACH_VALUE(field); if (phalcon_isset_property_zval(this_ptr, field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(value); } PHALCON_OBS_NVAR(referenced_field); phalcon_array_fetch(&referenced_field, referenced_fields, position, PH_NOISY_CC); PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VSV(condition, referenced_field, " = ?", position); phalcon_array_append(&conditions, condition, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_params, value, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah1, &hp1); } } else { if (phalcon_isset_property_zval(this_ptr, fields TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, fields, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(value); } PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VS(condition, referenced_fields, " = ?0"); phalcon_array_append(&conditions, condition, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_params, value, PH_SEPARATE TSRMLS_CC); } /** * Check if the virtual foreign key has extra conditions */ if (phalcon_array_isset_string(foreign_key, SS("conditions"))) { PHALCON_OBS_NVAR(extra_conditions); phalcon_array_fetch_string(&extra_conditions, foreign_key, SL("conditions"), PH_NOISY_CC); phalcon_array_append(&conditions, extra_conditions, PH_SEPARATE TSRMLS_CC); } /** * We don't trust the actual values in the object and then we're passing the values * using bound parameters */ PHALCON_INIT_NVAR(join_conditions); phalcon_fast_join_str(join_conditions, SL(" AND "), conditions TSRMLS_CC); PHALCON_INIT_NVAR(parameters); array_init_size(parameters, 2); phalcon_array_append(&parameters, join_conditions, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&parameters, SL("bind"), &bind_params, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Let's make the checking */ PHALCON_INIT_NVAR(rowcount); PHALCON_CALL_METHOD_PARAMS_1(rowcount, referenced_model, "count", parameters); if (zend_is_true(rowcount)) { /** * Create a new message */ if (phalcon_array_isset_string(foreign_key, SS("message"))) { PHALCON_OBS_NVAR(user_message); phalcon_array_fetch_string(&user_message, foreign_key, SL("message"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(user_message); PHALCON_CONCAT_SV(user_message, "Record is referenced by model ", relation_class); } /** * Create a message */ PHALCON_INIT_NVAR(type); ZVAL_STRING(type, "ConstraintViolation", 1); PHALCON_INIT_NVAR(message); object_init_ex(message, phalcon_mvc_model_message_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(message, "__construct", user_message, fields, type); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "appendmessage", message); PHALCON_INIT_NVAR(error); ZVAL_BOOL(error, 1); break; } } zend_hash_move_forward_ex(ah0, &hp0); } /** * Call validation fails event */ if (PHALCON_IS_TRUE(error)) { if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "onValidationFails", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_CALL_METHOD_NORETURN(this_ptr, "_canceloperation"); } RETURN_MM_FALSE; } } RETURN_MM_TRUE; } /** * Executes internal hooks before save a record * * @param Phalcon\Mvc\Model\MetadataInterface $metaData * @param boolean $exists * @param string $identityField * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _preSave){ zval *meta_data, *exists, *identity_field, *event_name = NULL; zval *status = NULL, *not_null, *data_type_numeric; zval *column_map = NULL, *automatic_attributes = NULL, *error = NULL; zval *null_value, *field = NULL, *is_null = NULL, *attribute_field = NULL; zval *exception_message = NULL, *value = NULL, *message = NULL, *type = NULL; zval *model_message = NULL, *skipped; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &meta_data, &exists, &identity_field) == FAILURE) { RETURN_MM_NULL(); } /** * Run Validation Callbacks Before */ if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "beforeValidation", 1); /** * Call the beforeValidation */ PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } if (!zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeValidationOnCreate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeValidationOnUpdate", 1); } /** * Call the specific beforeValidation event for the current action */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } /** * Check for Virtual foreign keys */ if (PHALCON_GLOBAL(orm).virtual_foreign_keys) { PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD(status, this_ptr, "_checkforeignkeys"); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } /** * Columns marked as not null are automatically validated by the ORM */ if (PHALCON_GLOBAL(orm).not_null_validations) { PHALCON_INIT_VAR(not_null); PHALCON_CALL_METHOD_PARAMS_1(not_null, meta_data, "getnotnullattributes", this_ptr); if (Z_TYPE_P(not_null) == IS_ARRAY) { /** * Gets the fields that are numeric, these are validated in a diferent way */ PHALCON_INIT_VAR(data_type_numeric); PHALCON_CALL_METHOD_PARAMS_1(data_type_numeric, meta_data, "getdatatypesnumeric", this_ptr); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * Get fields that must be omitted from the SQL generation */ if (zend_is_true(exists)) { PHALCON_INIT_VAR(automatic_attributes); PHALCON_CALL_METHOD_PARAMS_1(automatic_attributes, meta_data, "getautomaticupdateattributes", this_ptr); } else { PHALCON_INIT_NVAR(automatic_attributes); PHALCON_CALL_METHOD_PARAMS_1(automatic_attributes, meta_data, "getautomaticcreateattributes", this_ptr); } PHALCON_INIT_VAR(error); ZVAL_BOOL(error, 0); PHALCON_INIT_VAR(null_value); if (!phalcon_is_iterable(not_null, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); /** * We don't check fields that must be omitted */ if (!phalcon_array_isset(automatic_attributes, field)) { PHALCON_INIT_NVAR(is_null); ZVAL_BOOL(is_null, 0); if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, field); } /** * Field is null when: 1) is not set, 2) is numeric but its value is not numeric, * 3) is null or 4) is empty string */ if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); if (Z_TYPE_P(value) != IS_OBJECT) { if (!phalcon_array_isset(data_type_numeric, field)) { if (PHALCON_IS_EMPTY(value)) { PHALCON_INIT_NVAR(is_null); ZVAL_BOOL(is_null, 1); } } else { if (!phalcon_is_numeric(value)) { PHALCON_INIT_NVAR(is_null); ZVAL_BOOL(is_null, 1); } } } } else { PHALCON_INIT_NVAR(is_null); ZVAL_BOOL(is_null, 1); } if (PHALCON_IS_TRUE(is_null)) { if (!zend_is_true(exists)) { /** * The identity field can be null */ if (PHALCON_IS_EQUAL(field, identity_field)) { zend_hash_move_forward_ex(ah0, &hp0); continue; } } PHALCON_INIT_NVAR(message); PHALCON_CONCAT_VS(message, attribute_field, " is required"); PHALCON_INIT_NVAR(type); ZVAL_STRING(type, "PresenceOf", 1); /** * A implicit PresenceOf message is created */ PHALCON_INIT_NVAR(model_message); object_init_ex(model_message, phalcon_mvc_model_message_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(model_message, "__construct", message, attribute_field, type); phalcon_update_property_array_append(this_ptr, SL("_errorMessages"), model_message TSRMLS_CC); PHALCON_INIT_NVAR(error); ZVAL_BOOL(error, 1); } } zend_hash_move_forward_ex(ah0, &hp0); } if (PHALCON_IS_TRUE(error)) { if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "onValidationFails", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_CALL_METHOD_NORETURN(this_ptr, "_canceloperation"); } RETURN_MM_FALSE; } } } PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "validation", 1); /** * Call the main validation event */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "onValidationFails", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } RETURN_MM_FALSE; } /** * Run Validation */ if (PHALCON_GLOBAL(orm).events) { if (!zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidationOnCreate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidationOnUpdate", 1); } /** * Run Validation Callbacks After */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidation", 1); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeSave", 1); /** * Run Before Callbacks */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } if (zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeUpdate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeCreate", 1); } phalcon_update_property_bool(this_ptr, SL("_skipped"), 0 TSRMLS_CC); /** * The operation can be skipped here */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } /** * Always return true if the operation is skipped */ PHALCON_OBS_VAR(skipped); phalcon_read_property(&skipped, this_ptr, SL("_skipped"), PH_NOISY_CC); if (PHALCON_IS_TRUE(skipped)) { RETURN_MM_TRUE; } } RETURN_MM_TRUE; } /** * Executes internal events after save a record * * @param boolean $success * @param boolean $exists * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _postSave){ zval *success, *exists, *event_name = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &success, &exists) == FAILURE) { RETURN_MM_NULL(); } if (PHALCON_IS_TRUE(success)) { if (zend_is_true(exists)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "afterUpdate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterCreate", 1); } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterSave", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); RETURN_CCTOR(success); } PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "notSave", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_CALL_METHOD_NORETURN(this_ptr, "_canceloperation"); RETURN_MM_FALSE; } /** * Sends a pre-build INSERT SQL statement to the relational database system * * @param Phalcon\Mvc\Model\MetadataInterface $metaData * @param Phalcon\Db\AdapterInterface $connection * @param string $table * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _doLowInsert){ zval *meta_data, *connection, *table, *identity_field; zval *null_value, *bind_skip, *fields, *values; zval *bind_types, *attributes, *bind_data_types; zval *automatic_attributes, *column_map = NULL, *field = NULL; zval *attribute_field = NULL, *exception_message = NULL; zval *value = NULL, *bind_type = NULL, *default_value, *success; zval *sequence_name = NULL, *support_sequences, *source; zval *last_insert_id; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzz", &meta_data, &connection, &table, &identity_field) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(bind_skip); ZVAL_LONG(bind_skip, 1024); PHALCON_INIT_VAR(fields); array_init(fields); PHALCON_INIT_VAR(values); array_init(values); PHALCON_INIT_VAR(bind_types); array_init(bind_types); PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); PHALCON_INIT_VAR(bind_data_types); PHALCON_CALL_METHOD_PARAMS_1(bind_data_types, meta_data, "getbindtypes", this_ptr); PHALCON_INIT_VAR(automatic_attributes); PHALCON_CALL_METHOD_PARAMS_1(automatic_attributes, meta_data, "getautomaticcreateattributes", this_ptr); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * All fields in the model makes part or the INSERT */ if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); if (!phalcon_array_isset(automatic_attributes, field)) { /** * Check if the model has a column map */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, field); } /** * Check every attribute in the model except identity field */ if (!PHALCON_IS_EQUAL(field, identity_field)) { phalcon_array_append(&fields, field, PH_SEPARATE TSRMLS_CC); if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { if (!phalcon_array_isset(bind_data_types, field)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the table columns"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); phalcon_array_append(&values, value, PH_SEPARATE TSRMLS_CC); PHALCON_OBS_NVAR(bind_type); phalcon_array_fetch(&bind_type, bind_data_types, field, PH_NOISY_CC); phalcon_array_append(&bind_types, bind_type, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&values, null_value, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_types, bind_skip, PH_SEPARATE TSRMLS_CC); } } } zend_hash_move_forward_ex(ah0, &hp0); } /** * If there is an identity field we add it using "null" or "default" */ if (PHALCON_IS_NOT_FALSE(identity_field)) { PHALCON_INIT_VAR(default_value); PHALCON_CALL_METHOD(default_value, connection, "getdefaultidvalue"); phalcon_array_append(&fields, identity_field, PH_SEPARATE TSRMLS_CC); /** * Check if the model has a column map */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, identity_field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, identity_field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", identity_field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, identity_field); } if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); if (PHALCON_IS_EMPTY(value)) { phalcon_array_append(&values, default_value, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_data_types, bind_skip, PH_SEPARATE TSRMLS_CC); } else { /** * The field is valid we look for a bind value (normally int) */ if (!phalcon_array_isset(bind_data_types, identity_field)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Identity column '", identity_field, "\" isn't part of the table columns"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_array_append(&values, value, PH_SEPARATE TSRMLS_CC); PHALCON_OBS_NVAR(bind_type); phalcon_array_fetch(&bind_type, bind_data_types, identity_field, PH_NOISY_CC); phalcon_array_append(&bind_types, bind_type, PH_SEPARATE TSRMLS_CC); } } else { phalcon_array_append(&values, default_value, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_types, bind_skip, PH_SEPARATE TSRMLS_CC); } } /** * The low level insert is performed */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_4(success, connection, "insert", table, values, fields, bind_types); if (PHALCON_IS_NOT_FALSE(identity_field)) { /** * We check if the model have sequences */ PHALCON_INIT_VAR(sequence_name); PHALCON_INIT_VAR(support_sequences); PHALCON_CALL_METHOD(support_sequences, connection, "supportsequences"); if (PHALCON_IS_TRUE(support_sequences)) { if (phalcon_method_exists_ex(this_ptr, SS("getsequencename") TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD(sequence_name, this_ptr, "getsequencename"); } else { PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); PHALCON_INIT_NVAR(sequence_name); PHALCON_CONCAT_VSVS(sequence_name, source, "_", identity_field, "_seq"); } } /** * Recover the last "insert id" and assign it to the object */ PHALCON_INIT_VAR(last_insert_id); PHALCON_CALL_METHOD_PARAMS_1(last_insert_id, connection, "lastinsertid", sequence_name); phalcon_update_property_zval_zval(this_ptr, attribute_field, last_insert_id TSRMLS_CC); /** * Since the primary key was modified, we delete the _uniqueParams to force any * future update to re-build the primary key */ phalcon_update_property_null(this_ptr, SL("_uniqueParams") TSRMLS_CC); } RETURN_CCTOR(success); } /** * Sends a pre-build UPDATE SQL statement to the relational database system * * @param Phalcon\Mvc\Model\MetadataInterface $metaData * @param Phalcon\Db\AdapterInterface $connection * @param string|array $table * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, _doLowUpdate){ zval *meta_data, *connection, *table, *null_value; zval *bind_skip, *fields, *values, *bind_types; zval *bind_data_types, *non_primary, *automatic_attributes; zval *column_map = NULL, *field = NULL, *exception_message = NULL; zval *attribute_field = NULL, *value = NULL, *bind_type = NULL, *unique_key; zval *unique_params = NULL, *unique_types, *primary_keys; zval *conditions, *success; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &meta_data, &connection, &table) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(bind_skip); ZVAL_LONG(bind_skip, 1024); PHALCON_INIT_VAR(fields); array_init(fields); PHALCON_INIT_VAR(values); array_init(values); PHALCON_INIT_VAR(bind_types); array_init(bind_types); PHALCON_INIT_VAR(bind_data_types); PHALCON_CALL_METHOD_PARAMS_1(bind_data_types, meta_data, "getbindtypes", this_ptr); PHALCON_INIT_VAR(non_primary); PHALCON_CALL_METHOD_PARAMS_1(non_primary, meta_data, "getnonprimarykeyattributes", this_ptr); PHALCON_INIT_VAR(automatic_attributes); PHALCON_CALL_METHOD_PARAMS_1(automatic_attributes, meta_data, "getautomaticupdateattributes", this_ptr); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * We only make the update based on the non-primary attributes, values in primary * key attributes are ignored */ if (!phalcon_is_iterable(non_primary, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); if (!phalcon_array_isset(automatic_attributes, field)) { /** * Check a bind type for field to update */ if (!phalcon_array_isset(bind_data_types, field)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the table columns"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_array_append(&fields, field, PH_SEPARATE TSRMLS_CC); /** * Check if the model has a column map */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, field); } if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); phalcon_array_append(&values, value, PH_SEPARATE TSRMLS_CC); PHALCON_OBS_NVAR(bind_type); phalcon_array_fetch(&bind_type, bind_data_types, field, PH_NOISY_CC); phalcon_array_append(&bind_types, bind_type, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&values, null_value, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&bind_types, bind_skip, PH_SEPARATE TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_OBS_VAR(unique_key); phalcon_read_property(&unique_key, this_ptr, SL("_uniqueKey"), PH_NOISY_CC); PHALCON_OBS_VAR(unique_params); phalcon_read_property(&unique_params, this_ptr, SL("_uniqueParams"), PH_NOISY_CC); PHALCON_OBS_VAR(unique_types); phalcon_read_property(&unique_types, this_ptr, SL("_uniqueTypes"), PH_NOISY_CC); /** * When unique params is null we need to rebuild the bind params */ if (Z_TYPE_P(unique_params) != IS_ARRAY) { PHALCON_INIT_NVAR(unique_params); array_init(unique_params); PHALCON_INIT_VAR(primary_keys); PHALCON_CALL_METHOD_PARAMS_1(primary_keys, meta_data, "getprimarykeyattributes", this_ptr); if (!phalcon_is_iterable(primary_keys, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); /** * Check if the model has a column map */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, field)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, field, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", field, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, field); } if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); phalcon_array_append(&unique_params, value, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_append(&unique_params, null_value, PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah1, &hp1); } } /** * We build the conditions as an array */ PHALCON_INIT_VAR(conditions); array_init_size(conditions, 3); phalcon_array_update_string(&conditions, SL("conditions"), &unique_key, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&conditions, SL("bind"), &unique_params, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&conditions, SL("bindTypes"), &unique_types, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Perform the low level update */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_5(success, connection, "update", table, fields, values, conditions, bind_types); RETURN_CCTOR(success); } /** * * @param array $related */ PHP_METHOD(Phalcon_Mvc_Model, _preSaveRelatedRecords){ zval *connection, *related, *class_name, *manager; zval *record = NULL, *name = NULL, *relation = NULL, *type = NULL, *columns = NULL, *referenced_model = NULL; zval *referenced_fields = NULL, *status = NULL, *messages = NULL; zval *message = NULL, *referenced_value = NULL; HashTable *ah0, *ah1; HashPosition hp0, hp1; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &connection, &related) == FAILURE) { RETURN_MM_NULL(); } /** * Start an implicit transaction */ PHALCON_CALL_METHOD_NORETURN(connection, "begin"); PHALCON_INIT_VAR(class_name); phalcon_get_class(class_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD(manager, this_ptr, "getmodelsmanager"); if (!phalcon_is_iterable(related, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(name, ah0, hp0); PHALCON_GET_FOREACH_VALUE(record); /** * Try to get a relation with the same name */ PHALCON_INIT_NVAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", class_name, name); if (Z_TYPE_P(relation) == IS_OBJECT) { PHALCON_INIT_NVAR(type); PHALCON_CALL_METHOD(type, relation, "gettype"); /** * Only belongsTo relations are important here */ if (PHALCON_IS_LONG(type, 0)) { if (Z_TYPE_P(record) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Only objects can be stored as part of belongs-to relations"); return; } PHALCON_INIT_NVAR(columns); PHALCON_CALL_METHOD(columns, relation, "getfields"); PHALCON_INIT_NVAR(referenced_model); PHALCON_CALL_METHOD(referenced_model, relation, "getreferencedmodel"); PHALCON_INIT_NVAR(referenced_fields); PHALCON_CALL_METHOD(referenced_fields, relation, "getreferencedfields"); if (Z_TYPE_P(columns) == IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Not implemented"); return; } PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD(status, record, "save"); if (!zend_is_true(status)) { /** * Get the validation messages generated by the referenced model */ PHALCON_INIT_NVAR(messages); PHALCON_CALL_METHOD(messages, record, "getmessages"); if (!phalcon_is_iterable(messages, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(message); /** * Set the related model */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(message, "setmodel", record); /** * Appends the messages to the current model */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "appendmessage", message); zend_hash_move_forward_ex(ah1, &hp1); } /** * Rollback the implicit transaction */ PHALCON_CALL_METHOD_NORETURN(connection, "rollback"); RETURN_MM_FALSE; } /** * Read the attribute from the referenced model and assigns it to the current model */ PHALCON_INIT_NVAR(referenced_value); PHALCON_CALL_METHOD_PARAMS_1(referenced_value, record, "readattribute", referenced_fields); phalcon_update_property_zval_zval(this_ptr, columns, referenced_value TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_MM_TRUE; } /** * Save the related records assigned in the has-one/has-many relations * * @param Phalcon\Db\AdapterInterface $connection * @param Phalcon\Mvc\ModelInterface[] $related */ PHP_METHOD(Phalcon_Mvc_Model, _postSaveRelatedRecords){ zval *connection, *related, *class_name, *manager; zval *record = NULL, *name = NULL, *relation = NULL, *type = NULL, *columns = NULL, *referenced_model = NULL; zval *referenced_fields = NULL, *related_records = NULL; zval *exception_message = NULL, *value = NULL, *record_after = NULL; zval *status = NULL, *messages = NULL, *message = NULL; HashTable *ah0, *ah1, *ah2; HashPosition hp0, hp1, hp2; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &connection, &related) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(class_name); phalcon_get_class(class_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD(manager, this_ptr, "getmodelsmanager"); if (!phalcon_is_iterable(related, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(name, ah0, hp0); PHALCON_GET_FOREACH_VALUE(record); /** * Try to get a relation with the same name */ PHALCON_INIT_NVAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", class_name, name); if (Z_TYPE_P(relation) == IS_OBJECT) { PHALCON_INIT_NVAR(type); PHALCON_CALL_METHOD(type, relation, "gettype"); /** * Discard belongsTo relations */ if (PHALCON_IS_LONG(type, 0)) { zend_hash_move_forward_ex(ah0, &hp0); continue; } if (Z_TYPE_P(record) != IS_OBJECT) { if (Z_TYPE_P(record) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Only objects/arrays can be stored as part of has-many/has-one relations"); return; } } PHALCON_INIT_NVAR(columns); PHALCON_CALL_METHOD(columns, relation, "getfields"); PHALCON_INIT_NVAR(referenced_model); PHALCON_CALL_METHOD(referenced_model, relation, "getreferencedmodel"); PHALCON_INIT_NVAR(referenced_fields); PHALCON_CALL_METHOD(referenced_fields, relation, "getreferencedfields"); if (Z_TYPE_P(columns) == IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Not implemented"); return; } /** * Create an implicit array of has-many/has-one records */ if (Z_TYPE_P(record) == IS_OBJECT) { PHALCON_INIT_NVAR(related_records); array_init_size(related_records, 1); phalcon_array_append(&related_records, record, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(related_records, record); } if (!phalcon_isset_property_zval(this_ptr, columns TSRMLS_CC)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "The column '", columns, "' needs to be present in the model"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Get the value of the field from the current model */ PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, columns, PH_NOISY_CC); if (!phalcon_is_iterable(related_records, &ah1, &hp1, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah1, (void**) &hd, &hp1) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(record_after); /** * Assign the value to the */ PHALCON_CALL_METHOD_PARAMS_2_NORETURN(record_after, "writeattribute", referenced_fields, value); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD(status, record_after, "save"); if (!zend_is_true(status)) { /** * Get the validation messages generated by the referenced model */ PHALCON_INIT_NVAR(messages); PHALCON_CALL_METHOD(messages, record, "getmessages"); if (!phalcon_is_iterable(messages, &ah2, &hp2, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah2, (void**) &hd, &hp2) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(message); /** * Set the related model */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(message, "setmodel", record); /** * Appends the messages to the current model */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "appendmessage", message); zend_hash_move_forward_ex(ah2, &hp2); } /** * Rollback the implicit transaction */ PHALCON_CALL_METHOD_NORETURN(connection, "rollback"); RETURN_MM_FALSE; } zend_hash_move_forward_ex(ah1, &hp1); } } else { if (Z_TYPE_P(record) != IS_ARRAY) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "There is no defined relations for the model \"", class_name, "\" using alias \"", name, "\""); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } zend_hash_move_forward_ex(ah0, &hp0); } /** * Commit the implicit transaction */ PHALCON_CALL_METHOD_NORETURN(connection, "commit"); RETURN_MM_TRUE; } /** * Inserts or updates a model instance. Returning true on success or false otherwise. * *<code> * //Creating a new robot * $robot = new Robots(); * $robot->type = 'mechanical' * $robot->name = '<NAME>'; * $robot->year = 1952; * $robot->save(); * * //Updating a robot name * $robot = Robots::findFirst("id=100"); * $robot->name = "Biomass"; * $robot->save(); *</code> * * @param array $data * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, save){ zval *data = NULL, *meta_data, *attributes, *attribute = NULL; zval *value = NULL, *possible_setter = NULL, *connection, *related; zval *status = NULL, *schema, *source, *table = NULL, *exists, *empty_array; zval *identity_field, *success = NULL; zval *r0 = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &data) == FAILURE) { RETURN_MM_NULL(); } if (!data) { PHALCON_INIT_VAR(data); } PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); /** * Assign the values passed */ if (Z_TYPE_P(data) != IS_NULL) { if (Z_TYPE_P(data) == IS_ARRAY) { PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); if (phalcon_array_isset(data, attribute)) { /** * We check if the field has a setter */ PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, data, attribute, PH_NOISY_CC); PHALCON_INIT_NVAR(possible_setter); PHALCON_CONCAT_SV(possible_setter, "set", attribute); if (phalcon_method_exists(this_ptr, possible_setter TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, Z_STRVAL_P(possible_setter), value); } else { /** * Otherwise we assign the attribute directly */ phalcon_update_property_zval_zval(this_ptr, attribute, value TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } } else { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data passed to save() must be an array"); return; } } /** * Create/Get the current database connection */ PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); /** * Save related records in belongsTo relationships */ PHALCON_OBS_VAR(related); phalcon_read_property(&related, this_ptr, SL("_related"), PH_NOISY_CC); if (Z_TYPE_P(related) == IS_ARRAY) { PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, this_ptr, "_presaverelatedrecords", connection, related); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, this_ptr, "getschema"); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); if (zend_is_true(schema)) { PHALCON_INIT_VAR(table); array_init_size(table, 2); phalcon_array_append(&table, schema, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&table, source, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(table, source); } /** * We need to check if the record exists */ PHALCON_INIT_VAR(exists); PHALCON_CALL_METHOD_PARAMS_3(exists, this_ptr, "_exists", meta_data, connection, table); if (zend_is_true(exists)) { phalcon_update_property_long(this_ptr, SL("_operationMade"), 2 TSRMLS_CC); } else { phalcon_update_property_long(this_ptr, SL("_operationMade"), 1 TSRMLS_CC); } /** * Clean the messages */ PHALCON_INIT_VAR(empty_array); array_init(empty_array); phalcon_update_property_zval(this_ptr, SL("_errorMessages"), empty_array TSRMLS_CC); /** * Query the identity field */ PHALCON_INIT_VAR(identity_field); PHALCON_CALL_METHOD_PARAMS_1(identity_field, meta_data, "getidentityfield", this_ptr); /** * _preSave() makes all the validations */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_3(status, this_ptr, "_presave", meta_data, exists, identity_field); if (PHALCON_IS_FALSE(status)) { /** * Rollback the current transaction if there was validation errors */ if (Z_TYPE_P(related) == IS_ARRAY) { PHALCON_CALL_METHOD_NORETURN(connection, "rollback"); } RETURN_MM_FALSE; } /** * Depending if the record exists we do an update or an insert operation */ if (zend_is_true(exists)) { PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_3(success, this_ptr, "_dolowupdate", meta_data, connection, table); } else { PHALCON_INIT_NVAR(success); PHALCON_CALL_METHOD_PARAMS_4(success, this_ptr, "_dolowinsert", meta_data, connection, table, identity_field); } /** * Change the dirty state to persistent */ if (zend_is_true(success)) { phalcon_update_property_long(this_ptr, SL("_dirtyState"), 0 TSRMLS_CC); } /** * _postSave() makes all the validations */ if (PHALCON_GLOBAL(orm).events) { PHALCON_INIT_VAR(r0); PHALCON_CALL_METHOD_PARAMS_2(r0, this_ptr, "_postsave", success, exists); PHALCON_CPY_WRT(success, r0); } if (Z_TYPE_P(related) == IS_ARRAY) { /** * Rollbacks the implicit transaction if the master save has failed */ if (PHALCON_IS_FALSE(success)) { PHALCON_CALL_METHOD_NORETURN(connection, "rollback"); RETURN_MM_FALSE; } /** * Save the post-related records */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, this_ptr, "_postsaverelatedrecords", connection, related); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } RETURN_CCTOR(success); } /** * Inserts a model instance. If the instance already exists in the persistance it will throw an exception * Returning true on success or false otherwise. * *<code> * //Creating a new robot * $robot = new Robots(); * $robot->type = 'mechanical' * $robot->name = '<NAME>'; * $robot->year = 1952; * $robot->create(); * * //Passing an array to create * $robot = new Robots(); * $robot->create(array( * 'type' => 'mechanical', * 'name' => '<NAME>', * 'year' => 1952 * )); *</code> * * @param array $data * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, create){ zval *data = NULL, *meta_data, *column_map = NULL, *attributes; zval *attribute = NULL, *attribute_field = NULL, *exception_message = NULL; zval *value = NULL, *possible_setter = NULL, *connection, *exists; zval *field, *type, *message, *model_message, *messages; zval *success; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &data) == FAILURE) { RETURN_MM_NULL(); } if (!data) { PHALCON_INIT_VAR(data); } PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); /** * Assign the values passed */ if (Z_TYPE_P(data) != IS_NULL) { if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data passed to create() must be an array"); return; } if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * We assign the fields starting from the current attributes in the model */ PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); /** * Check if we need to rename the field */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, attribute)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, attribute, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", attribute, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, attribute); } /** * Check if we there is data for the field */ if (phalcon_array_isset(data, attribute_field)) { /** * The value in the array passed */ PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, data, attribute_field, PH_NOISY_CC); /** * Check if the field has a posible setter */ PHALCON_INIT_NVAR(possible_setter); PHALCON_CONCAT_SV(possible_setter, "set", attribute_field); if (phalcon_method_exists(this_ptr, possible_setter TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, Z_STRVAL_P(possible_setter), value); } else { phalcon_update_property_zval_zval(this_ptr, attribute_field, value TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } } /** * Get the current connection */ PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); /** * A 'exists' confirmation is performed first */ PHALCON_INIT_VAR(exists); PHALCON_CALL_METHOD_PARAMS_2(exists, this_ptr, "_exists", meta_data, connection); /** * If the record already exists we must throw an exception */ if (zend_is_true(exists)) { PHALCON_INIT_VAR(field); PHALCON_INIT_VAR(type); ZVAL_STRING(type, "InvalidCreateAttempt", 1); PHALCON_INIT_VAR(message); ZVAL_STRING(message, "Record cannot be created because it already exists", 1); PHALCON_INIT_VAR(model_message); object_init_ex(model_message, phalcon_mvc_model_message_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(model_message, "__construct", message, field, type); PHALCON_INIT_VAR(messages); array_init_size(messages, 1); phalcon_array_append(&messages, model_message, PH_SEPARATE TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_errorMessages"), messages TSRMLS_CC); RETURN_MM_FALSE; } /** * Using save() anyways */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD(success, this_ptr, "save"); RETURN_CCTOR(success); } /** * Updates a model instance. If the instance doesn't exist in the persistance it will throw an exception * Returning true on success or false otherwise. * *<code> * //Updating a robot name * $robot = Robots::findFirst("id=100"); * $robot->name = "Biomass"; * $robot->update(); *</code> * * @param array $data * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, update){ zval *data = NULL, *meta_data = NULL, *column_map = NULL, *attributes; zval *attribute = NULL, *attribute_field = NULL, *exception_message = NULL; zval *value = NULL, *possible_setter = NULL, *dirty_state; zval *connection, *exists, *field, *type, *message; zval *model_message, *messages, *success; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &data) == FAILURE) { RETURN_MM_NULL(); } if (!data) { PHALCON_INIT_VAR(data); } PHALCON_INIT_VAR(meta_data); /** * Assign the values bassed on the passed */ if (Z_TYPE_P(data) != IS_NULL) { if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Data passed to update() must be an array"); return; } PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * We assign the fields starting from the current attributes in the model */ PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); /** * Check if we need to rename the field */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, attribute)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, attribute, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", attribute, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, attribute); } /** * Check if we there is data for the field */ if (phalcon_array_isset(data, attribute_field)) { PHALCON_OBS_NVAR(value); phalcon_array_fetch(&value, data, attribute_field, PH_NOISY_CC); PHALCON_INIT_NVAR(possible_setter); PHALCON_CONCAT_SV(possible_setter, "set", attribute_field); if (phalcon_method_exists(this_ptr, possible_setter TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, Z_STRVAL_P(possible_setter), value); } else { phalcon_update_property_zval_zval(this_ptr, attribute_field, value TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } } /** * We don't check if the record exists if the record is already checked */ PHALCON_OBS_VAR(dirty_state); phalcon_read_property(&dirty_state, this_ptr, SL("_dirtyState"), PH_NOISY_CC); if (zend_is_true(dirty_state)) { if (Z_TYPE_P(meta_data) == IS_NULL) { PHALCON_INIT_NVAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); } PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); PHALCON_INIT_VAR(exists); PHALCON_CALL_METHOD_PARAMS_2(exists, this_ptr, "_exists", meta_data, connection); if (!zend_is_true(exists)) { PHALCON_INIT_VAR(field); PHALCON_INIT_VAR(type); ZVAL_STRING(type, "InvalidUpdateAttempt", 1); PHALCON_INIT_VAR(message); ZVAL_STRING(message, "Record cannot be updated because it does not exist", 1); PHALCON_INIT_VAR(model_message); object_init_ex(model_message, phalcon_mvc_model_message_ce); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(model_message, "__construct", message, field, type); PHALCON_INIT_VAR(messages); array_init_size(messages, 1); phalcon_array_append(&messages, model_message, PH_SEPARATE TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_errorMessages"), messages TSRMLS_CC); RETURN_MM_FALSE; } } /** * Call save() anyways */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD(success, this_ptr, "save"); RETURN_CCTOR(success); } /** * Deletes a model instance. Returning true on success or false otherwise. * * <code> *$robot = Robots::findFirst("id=100"); *$robot->delete(); * *foreach(Robots::find("type = 'mechanical'") as $robot){ * $robot->delete(); *} * </code> * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model, delete){ zval *meta_data, *connection, *empty_array, *check_foreign_keys; zval *values, *bind_types, *conditions, *primary_keys; zval *bind_data_types, *column_map = NULL, *primary_key = NULL; zval *exception_message = NULL, *attribute_field = NULL; zval *value = NULL, *escaped_field = NULL, *primary_condition = NULL; zval *bind_type = NULL, *delete_conditions, *event_name = NULL; zval *status, *skipped, *schema, *source, *table = NULL, *success; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); /** * Operation made is OP_DELETE */ phalcon_update_property_long(this_ptr, SL("_operationMade"), 3 TSRMLS_CC); PHALCON_INIT_VAR(empty_array); array_init(empty_array); phalcon_update_property_zval(this_ptr, SL("_errorMessages"), empty_array TSRMLS_CC); /** * Check if deleting the record violates a virtual foreign key */ if (PHALCON_GLOBAL(orm).virtual_foreign_keys) { PHALCON_INIT_VAR(check_foreign_keys); PHALCON_CALL_METHOD(check_foreign_keys, this_ptr, "_checkforeignkeysreverse"); if (PHALCON_IS_FALSE(check_foreign_keys)) { RETURN_MM_FALSE; } } PHALCON_INIT_VAR(values); array_init(values); PHALCON_INIT_VAR(bind_types); array_init(bind_types); PHALCON_INIT_VAR(conditions); array_init(conditions); PHALCON_INIT_VAR(primary_keys); PHALCON_CALL_METHOD_PARAMS_1(primary_keys, meta_data, "getprimarykeyattributes", this_ptr); PHALCON_INIT_VAR(bind_data_types); PHALCON_CALL_METHOD_PARAMS_1(bind_data_types, meta_data, "getbindtypes", this_ptr); if (PHALCON_GLOBAL(orm).column_renaming) { PHALCON_INIT_VAR(column_map); PHALCON_CALL_METHOD_PARAMS_1(column_map, meta_data, "getcolumnmap", this_ptr); } else { PHALCON_INIT_NVAR(column_map); } /** * Create a condition from the primary keys */ if (!phalcon_is_iterable(primary_keys, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(primary_key); /** * Every column part of the primary key must be in the bind data types */ if (!phalcon_array_isset(bind_data_types, primary_key)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", primary_key, "\" isn't part of the table columns"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Take the column values based on the column map if any */ if (Z_TYPE_P(column_map) == IS_ARRAY) { if (phalcon_array_isset(column_map, primary_key)) { PHALCON_OBS_NVAR(attribute_field); phalcon_array_fetch(&attribute_field, column_map, primary_key, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Column '", primary_key, "\" isn't part of the column map"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } } else { PHALCON_CPY_WRT(attribute_field, primary_key); } /** * If the attribute is currently set in the object add it to the conditions */ if (phalcon_isset_property_zval(this_ptr, attribute_field TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute_field, PH_NOISY_CC); phalcon_array_append(&values, value, PH_SEPARATE TSRMLS_CC); /** * Escape the column identifier */ PHALCON_INIT_NVAR(escaped_field); PHALCON_CALL_METHOD_PARAMS_1(escaped_field, connection, "escapeidentifier", primary_key); PHALCON_INIT_NVAR(primary_condition); PHALCON_CONCAT_VS(primary_condition, escaped_field, " = ?"); phalcon_array_append(&conditions, primary_condition, PH_SEPARATE TSRMLS_CC); PHALCON_OBS_NVAR(bind_type); phalcon_array_fetch(&bind_type, bind_data_types, primary_key, PH_NOISY_CC); phalcon_array_append(&bind_types, bind_type, PH_SEPARATE TSRMLS_CC); } else { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Cannot delete the record because one of the primary key attributes isn't set"); return; } zend_hash_move_forward_ex(ah0, &hp0); } /** * Join the conditions in the array using an AND operator */ PHALCON_INIT_VAR(delete_conditions); phalcon_fast_join_str(delete_conditions, SL(" AND "), conditions TSRMLS_CC); if (PHALCON_GLOBAL(orm).events) { phalcon_update_property_bool(this_ptr, SL("_skipped"), 0 TSRMLS_CC); PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "beforeDelete", 1); PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } else { /** * The operation can be skipped */ PHALCON_OBS_VAR(skipped); phalcon_read_property(&skipped, this_ptr, SL("_skipped"), PH_NOISY_CC); if (PHALCON_IS_TRUE(skipped)) { RETURN_MM_TRUE; } } } PHALCON_INIT_VAR(schema); PHALCON_CALL_METHOD(schema, this_ptr, "getschema"); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); if (zend_is_true(schema)) { PHALCON_INIT_VAR(table); array_init_size(table, 2); phalcon_array_append(&table, schema, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&table, source, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(table, source); } /** * Do the deletion */ PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_4(success, connection, "delete", table, delete_conditions, values, bind_types); if (PHALCON_GLOBAL(orm).events) { if (zend_is_true(success)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterDelete", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } } /** * Force perform the record existence checking again */ phalcon_update_property_long(this_ptr, SL("_dirtyState"), 2 TSRMLS_CC); RETURN_CCTOR(success); } /** * Returns the type of the latest operation performed by the ORM * Returns one of the OP_* class constants * * @return int */ PHP_METHOD(Phalcon_Mvc_Model, getOperationMade){ RETURN_MEMBER(this_ptr, "_operationMade"); } /** * Skips the current operation forcing a success state * * @param boolean $skip */ PHP_METHOD(Phalcon_Mvc_Model, skipOperation){ zval *skip; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &skip) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_skipped"), skip TSRMLS_CC); } /** * Reads an attribute value by its name * * <code> * echo $robot->readAttribute('name'); * </code> * * @param string $attribute * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, readAttribute){ zval *attribute, *attribute_value; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &attribute) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_isset_property_zval(this_ptr, attribute TSRMLS_CC)) { PHALCON_OBS_VAR(attribute_value); phalcon_read_property_zval(&attribute_value, this_ptr, attribute, PH_NOISY_CC); RETURN_CCTOR(attribute_value); } RETURN_MM_NULL(); } /** * Writes an attribute value by its name * * <code> * $robot->writeAttribute('name', 'Rosey'); * </code> * * @param string $attribute * @param mixed $value */ PHP_METHOD(Phalcon_Mvc_Model, writeAttribute){ zval *attribute, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &attribute, &value) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval_zval(this_ptr, attribute, value TSRMLS_CC); } /** * Sets a list of attributes that must be skipped from the * generated INSERT/UPDATE statement * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->skipAttributes(array('price')); * } * *} *</code> * * @param array $attributes */ PHP_METHOD(Phalcon_Mvc_Model, skipAttributes){ zval *attributes, *null_value, *keys_attributes; zval *attribute = NULL, *meta_data; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &attributes) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(attributes) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Attributes must be an array"); return; } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(keys_attributes); array_init(keys_attributes); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); phalcon_array_update_zval(&keys_attributes, attribute, &null_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(meta_data, "setautomaticcreateattributes", this_ptr, keys_attributes); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(meta_data, "setautomaticupdateattributes", this_ptr, keys_attributes); PHALCON_MM_RESTORE(); } /** * Sets a list of attributes that must be skipped from the * generated INSERT statement * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->skipAttributesOnUpdate(array('created_at')); * } * *} *</code> * * @param array $attributes */ PHP_METHOD(Phalcon_Mvc_Model, skipAttributesOnCreate){ zval *attributes, *null_value, *keys_attributes; zval *attribute = NULL, *meta_data; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &attributes) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(attributes) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Attributes must be an array"); return; } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(keys_attributes); array_init(keys_attributes); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); phalcon_array_update_zval(&keys_attributes, attribute, &null_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(meta_data, "setautomaticcreateattributes", this_ptr, keys_attributes); PHALCON_MM_RESTORE(); } /** * Sets a list of attributes that must be skipped from the * generated UPDATE statement * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->skipAttributesOnUpdate(array('modified_in')); * } * *} *</code> * * @param array $attributes */ PHP_METHOD(Phalcon_Mvc_Model, skipAttributesOnUpdate){ zval *attributes, *null_value, *keys_attributes; zval *attribute = NULL, *meta_data; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &attributes) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(attributes) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Attributes must be an array"); return; } PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(keys_attributes); array_init(keys_attributes); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); phalcon_array_update_zval(&keys_attributes, attribute, &null_value, PH_COPY | PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(meta_data, "setautomaticupdateattributes", this_ptr, keys_attributes); PHALCON_MM_RESTORE(); } /** * Setup a 1-1 relation between two models * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->hasOne('id', 'RobotsDescription', 'robots_id'); * } * *} *</code> * * @param mixed $fields * @param string $referenceModel * @param mixed $referencedFields * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model, hasOne){ zval *fields, *reference_model, *referenced_fields; zval *options = NULL, *manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &fields, &reference_model, &referenced_fields, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_5_NORETURN(manager, "addhasone", this_ptr, fields, reference_model, referenced_fields, options); PHALCON_MM_RESTORE(); } /** * Setup a relation reverse 1-1 between two models * *<code> * *class RobotsParts extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->belongsTo('robots_id', 'Robots', 'id'); * } * *} *</code> * * @param mixed $fields * @param string $referenceModel * @param mixed $referencedFields * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model, belongsTo){ zval *fields, *reference_model, *referenced_fields; zval *options = NULL, *manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &fields, &reference_model, &referenced_fields, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_5_NORETURN(manager, "addbelongsto", this_ptr, fields, reference_model, referenced_fields, options); PHALCON_MM_RESTORE(); } /** * Setup a relation 1-n between two models * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->hasMany('id', 'RobotsParts', 'robots_id'); * } * *} *</code> * * @param mixed $fields * @param string $referenceModel * @param mixed $referencedFields * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model, hasMany){ zval *fields, *reference_model, *referenced_fields; zval *options = NULL, *manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &fields, &reference_model, &referenced_fields, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_5_NORETURN(manager, "addhasmany", this_ptr, fields, reference_model, referenced_fields, options); PHALCON_MM_RESTORE(); } /** * Setup a relation n-n between two models through an intermediate relation * *<code> * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * //A reference relation must be set * $this->hasMany('id', 'RobotsParts', 'robots_id'); * * //Setup a many-to-many relation to Parts through RobotsParts * $this->hasManyThrough('Parts', 'RobotsParts'); * } * *} *</code> * * @param string $referenceModel * @param string $throughRelation * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model, hasManyThrough){ zval *reference_model, *through_relation; zval *options = NULL, *manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|z", &reference_model, &through_relation, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_3_NORETURN(manager, "addhasmanythrough", this_ptr, reference_model, options); PHALCON_MM_RESTORE(); } /** * Setups a behavior in a model * *<code> * *use Phalcon\Mvc\Model\Behaviors\Timestampable; * *class Robots extends \Phalcon\Mvc\Model *{ * * public function initialize() * { * $this->addBehavior(new Timestampable( * 'onCreate' => array( * 'field' => 'created_at', * 'format' => 'Y-m-d' * ) * )); * } * *} *</code> * * @param Phalcon\Mvc\Model\BehaviorInterface $behavior */ PHP_METHOD(Phalcon_Mvc_Model, addBehavior){ zval *behavior, *manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &behavior) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(manager, "addbehavior", this_ptr, behavior); PHALCON_MM_RESTORE(); } /** * Returns related records based on defined relations * * @param string $alias * @param array $arguments * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model, getRelated){ zval *alias, *arguments = NULL, *manager, *class_name; zval *relation, *exception_message, *call_object; zval *model_args, *result; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &alias, &arguments) == FAILURE) { RETURN_MM_NULL(); } if (!arguments) { PHALCON_INIT_VAR(arguments); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(class_name); phalcon_get_class(class_name, this_ptr, 0 TSRMLS_CC); /** * Query the relation by alias */ PHALCON_INIT_VAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", class_name, alias); if (Z_TYPE_P(relation) != IS_OBJECT) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "There is no defined relations for the model \"", class_name, "\" using alias \"", alias, "\""); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Call the 'getRelationRecords' in the models manager */ PHALCON_INIT_VAR(call_object); array_init_size(call_object, 2); phalcon_array_append(&call_object, manager, PH_SEPARATE TSRMLS_CC); add_next_index_stringl(call_object, SL("getRelationRecords"), 1); PHALCON_INIT_VAR(model_args); array_init_size(model_args, 4); phalcon_array_append(&model_args, relation, PH_SEPARATE TSRMLS_CC); add_next_index_null(model_args); phalcon_array_append(&model_args, this_ptr, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&model_args, arguments, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(result); PHALCON_CALL_USER_FUNC_ARRAY(result, call_object, model_args); RETURN_CCTOR(result); } /** * Returns related records defined relations depending on the method name * * @param string $modelName * @param string $method * @param array $arguments * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, _getRelatedRecords){ zval *model_name, *method, *arguments, *manager; zval *relation = NULL, *query_method = NULL, *alias = NULL, *extra_args = NULL; zval *call_args, *call_object, *result; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &model_name, &method, &arguments) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(manager); phalcon_read_property(&manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(relation); ZVAL_BOOL(relation, 0); PHALCON_INIT_VAR(query_method); /** * Calling find/findFirst if the method starts with "get" */ if (phalcon_start_with_str(method, SL("get"))) { PHALCON_INIT_VAR(alias); phalcon_substr(alias, method, 3, 0 TSRMLS_CC); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", model_name, alias); } /** * Calling count if the method starts with "count" */ if (Z_TYPE_P(relation) != IS_OBJECT) { if (phalcon_start_with_str(method, SL("count"))) { ZVAL_STRING(query_method, "count", 1); PHALCON_INIT_NVAR(alias); phalcon_substr(alias, method, 5, 0 TSRMLS_CC); PHALCON_INIT_NVAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", model_name, alias); } } /** * If the relation was found perform the query via the models manager */ if (Z_TYPE_P(relation) == IS_OBJECT) { if (phalcon_array_isset_long(arguments, 0)) { PHALCON_OBS_VAR(extra_args); phalcon_array_fetch_long(&extra_args, arguments, 0, PH_NOISY_CC); } else { PHALCON_INIT_NVAR(extra_args); } PHALCON_INIT_VAR(call_args); array_init_size(call_args, 4); phalcon_array_append(&call_args, relation, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&call_args, query_method, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&call_args, this_ptr, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&call_args, extra_args, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(call_object); array_init_size(call_object, 2); phalcon_array_append(&call_object, manager, PH_SEPARATE TSRMLS_CC); add_next_index_stringl(call_object, SL("getRelationRecords"), 1); PHALCON_INIT_VAR(result); PHALCON_CALL_USER_FUNC_ARRAY(result, call_object, call_args); RETURN_CCTOR(result); } RETURN_MM_NULL(); } /** * Handles method calls when a method is not implemented * * @param string $method * @param array $arguments * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, __call){ zval *method, *arguments = NULL, *model_name, *records; zval *models_manager, *status, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &method, &arguments) == FAILURE) { RETURN_MM_NULL(); } if (!arguments) { PHALCON_INIT_VAR(arguments); array_init(arguments); } PHALCON_INIT_VAR(model_name); phalcon_get_class(model_name, this_ptr, 0 TSRMLS_CC); /** * Check if there is a default action using the magic getter */ PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD_PARAMS_3(records, this_ptr, "_getrelatedrecords", model_name, method, arguments); if (Z_TYPE_P(records) != IS_NULL) { RETURN_CCTOR(records); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Try to find a replacement for the missing method in a behavior/listener */ PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_3(status, models_manager, "missingmethod", this_ptr, method, arguments); if (Z_TYPE_P(status) != IS_NULL) { RETURN_CCTOR(status); } /** * The method doesn't exist throw an exception */ PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "The method \"", method, "\" doesn't exist on model \"", model_name, "\""); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } /** * Handles method calls when a static method is not implemented * * @param string $method * @param array $arguments * @return mixed */ PHP_METHOD(Phalcon_Mvc_Model, __callStatic){ zval *method, *arguments = NULL, *extra_method = NULL, *type = NULL; zval *model_name, *exception_message = NULL, *value; zval *uncamelized, *conditions, *bind_params; zval *parameters, *result; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &method, &arguments) == FAILURE) { RETURN_MM_NULL(); } if (!arguments) { PHALCON_INIT_VAR(arguments); } PHALCON_INIT_VAR(extra_method); /** * Check if the method starts with 'findFirst' */ if (phalcon_start_with_str(method, SL("findFirstBy"))) { PHALCON_INIT_VAR(type); ZVAL_STRING(type, "findFirst", 1); phalcon_substr(extra_method, method, 11, 0 TSRMLS_CC); } /** * Check if the method starts with 'find' */ if (Z_TYPE_P(extra_method) == IS_NULL) { if (phalcon_start_with_str(method, SL("findBy"))) { PHALCON_INIT_NVAR(type); ZVAL_STRING(type, "find", 1); PHALCON_INIT_NVAR(extra_method); phalcon_substr(extra_method, method, 6, 0 TSRMLS_CC); } } /** * The called class is the model */ PHALCON_INIT_VAR(model_name); phalcon_get_called_class(model_name TSRMLS_CC); if (!zend_is_true(extra_method)) { /** * The method doesn't exist throw an exception */ PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVSVS(exception_message, "The static method \"", method, "\" doesn't exist on model \"", model_name, "\""); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } if (!phalcon_array_isset_long(arguments, 0)) { PHALCON_INIT_NVAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "The static method \"", method, "\" requires one argument"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } PHALCON_OBS_VAR(value); phalcon_array_fetch_long(&value, arguments, 0, PH_NOISY_CC); /** * Get the real method name */ PHALCON_INIT_VAR(uncamelized); phalcon_uncamelize(uncamelized, extra_method TSRMLS_CC); PHALCON_INIT_VAR(conditions); PHALCON_CONCAT_VS(conditions, uncamelized, " = ?0"); PHALCON_INIT_VAR(bind_params); array_init_size(bind_params, 1); phalcon_array_append(&bind_params, value, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(parameters); array_init_size(parameters, 2); phalcon_array_update_string(&parameters, SL("conditions"), &conditions, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&parameters, SL("bind"), &bind_params, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Execute the query */ PHALCON_INIT_VAR(result); PHALCON_CALL_STATIC_ZVAL_PARAMS_1(result, model_name, Z_STRVAL_P(type), parameters); RETURN_CCTOR(result); } /** * Magic method to assign values to the the model * * @param string $property * @param mixed $value */ PHP_METHOD(Phalcon_Mvc_Model, __set){ zval *property, *value, *is_model, *lower_property = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &property, &value) == FAILURE) { RETURN_MM_NULL(); } /** * Values are probably relationships if they are objects */ if (Z_TYPE_P(value) == IS_OBJECT) { PHALCON_INIT_VAR(is_model); phalcon_instance_of(is_model, value, phalcon_mvc_modelinterface_ce TSRMLS_CC); if (zend_is_true(is_model)) { PHALCON_INIT_VAR(lower_property); phalcon_fast_strtolower(lower_property, property); phalcon_update_property_zval_zval(this_ptr, lower_property, value TSRMLS_CC); phalcon_update_property_array(this_ptr, SL("_related"), lower_property, value TSRMLS_CC); phalcon_update_property_long(this_ptr, SL("_dirtyState"), 1 TSRMLS_CC); RETURN_CCTOR(value); } } /** * Check if the value is an array */ if (Z_TYPE_P(value) == IS_ARRAY) { PHALCON_INIT_NVAR(lower_property); phalcon_fast_strtolower(lower_property, property); phalcon_update_property_array(this_ptr, SL("_related"), lower_property, value TSRMLS_CC); phalcon_update_property_long(this_ptr, SL("_dirtyState"), 1 TSRMLS_CC); RETURN_CCTOR(value); } /** * Fallback assigning the value to the instance */ phalcon_update_property_zval_zval(this_ptr, property, value TSRMLS_CC); RETURN_CCTOR(value); } /** * Magic method to get related records using the relation alias as a property * * @param string $property * @return Phalcon\Mvc\Model\Resultset */ PHP_METHOD(Phalcon_Mvc_Model, __get){ zval *property, *model_name, *manager, *lower_property; zval *relation, *call_args, *call_object, *result; zval *is_simple_model, *error_msg; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &property) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(model_name); phalcon_get_class(model_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD(manager, this_ptr, "getmodelsmanager"); PHALCON_INIT_VAR(lower_property); phalcon_fast_strtolower(lower_property, property); /** * Check if the property is a relationship */ PHALCON_INIT_VAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", model_name, lower_property); if (Z_TYPE_P(relation) == IS_OBJECT) { PHALCON_INIT_VAR(call_args); array_init_size(call_args, 4); phalcon_array_append(&call_args, relation, PH_SEPARATE TSRMLS_CC); add_next_index_null(call_args); phalcon_array_append(&call_args, this_ptr, PH_SEPARATE TSRMLS_CC); add_next_index_null(call_args); PHALCON_INIT_VAR(call_object); array_init_size(call_object, 2); phalcon_array_append(&call_object, manager, PH_SEPARATE TSRMLS_CC); add_next_index_stringl(call_object, SL("getRelationRecords"), 1); /** * Get the related records */ PHALCON_INIT_VAR(result); PHALCON_CALL_USER_FUNC_ARRAY(result, call_object, call_args); /** * Assign the result to the object */ if (Z_TYPE_P(result) == IS_OBJECT) { /** * We assign the result to the instance avoiding future queries */ phalcon_update_property_zval_zval(this_ptr, lower_property, result TSRMLS_CC); /** * For belongs-to relations we store the object in the related bag */ PHALCON_INIT_VAR(is_simple_model); phalcon_instance_of(is_simple_model, result, phalcon_mvc_modelinterface_ce TSRMLS_CC); if (PHALCON_IS_TRUE(is_simple_model)) { phalcon_update_property_array(this_ptr, SL("_related"), lower_property, result TSRMLS_CC); } } RETURN_CCTOR(result); } /** * A notice is shown if the property is not defined and it isn't a relationship */ PHALCON_INIT_VAR(error_msg); PHALCON_CONCAT_SVSV(error_msg, "Access to undefined property ", model_name, "::", property); PHALCON_CALL_FUNC_PARAMS_1_NORETURN("trigger_error", error_msg); RETURN_MM_NULL(); } /** * Magic method to check if a property is a valid relation * * @param string $property */ PHP_METHOD(Phalcon_Mvc_Model, __isset){ zval *property, *model_name, *manager, *relation; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &property) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(model_name); phalcon_get_class(model_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD(manager, this_ptr, "getmodelsmanager"); /** * Check if the property is a relationship */ PHALCON_INIT_VAR(relation); PHALCON_CALL_METHOD_PARAMS_2(relation, manager, "getrelationbyalias", model_name, property); if (Z_TYPE_P(relation) == IS_OBJECT) { RETURN_MM_TRUE; } RETURN_MM_FALSE; } /** * Serializes the object ignoring connections or static properties * * @return string */ PHP_METHOD(Phalcon_Mvc_Model, serialize){ zval *meta_data, *attributes, *null_value, *data; zval *attribute = NULL, *value = NULL, *serialize; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); /** * We get the model's attributes to only serialize them */ PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(data); array_init(data); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); if (phalcon_isset_property_zval(this_ptr, attribute TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute, PH_NOISY_CC); phalcon_array_update_zval(&data, attribute, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&data, attribute, &null_value, PH_COPY | PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah0, &hp0); } /** * Use the standard serialize function to serialize the array data */ PHALCON_INIT_VAR(serialize); PHALCON_CALL_FUNC_PARAMS_1(serialize, "serialize", data); RETURN_CCTOR(serialize); } /** * Unserializes the object from a serialized string * * @param string $data */ PHP_METHOD(Phalcon_Mvc_Model, unserialize){ zval *data, *attributes, *dependency_injector; zval *service, *manager, *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(data) == IS_STRING) { PHALCON_INIT_VAR(attributes); PHALCON_CALL_FUNC_PARAMS_1(attributes, "unserialize", data); if (Z_TYPE_P(attributes) == IS_ARRAY) { /** * Obtain the default DI */ PHALCON_INIT_VAR(dependency_injector); PHALCON_CALL_STATIC(dependency_injector, "phalcon\\di", "getdefault"); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ORM"); return; } /** * Update the dependency injector */ phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); /** * Gets the default modelsManager service */ PHALCON_INIT_VAR(service); ZVAL_STRING(service, "modelsManager", 1); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD_PARAMS_1(manager, dependency_injector, "getshared", service); if (Z_TYPE_P(manager) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The injected service 'modelsManager' is not valid"); return; } /** * Update the models manager */ phalcon_update_property_zval(this_ptr, SL("_modelsManager"), manager TSRMLS_CC); /** * Try to initialize the model */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(manager, "initialize", this_ptr); /** * Update the objects attributes */ if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); phalcon_update_property_zval_zval(this_ptr, key, value TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_MM_NULL(); } } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid serialization data"); return; } /** * Returns a simple representation of the object that can be used with var_dump * *<code> * var_dump($robot->dump()); *</code> * * @return array */ PHP_METHOD(Phalcon_Mvc_Model, dump){ zval *array_data; PHALCON_MM_GROW(); PHALCON_INIT_VAR(array_data); PHALCON_CALL_FUNC_PARAMS_1(array_data, "get_object_vars", this_ptr); RETURN_CCTOR(array_data); } /** * Returns the instance as an array representation * *<code> * print_r($robot->toArray()); *</code> * * @return array */ PHP_METHOD(Phalcon_Mvc_Model, toArray){ zval *meta_data, *data, *null_value, *attributes; zval *attribute = NULL, *value = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD(meta_data, this_ptr, "getmodelsmetadata"); PHALCON_INIT_VAR(data); array_init(data); PHALCON_INIT_VAR(null_value); PHALCON_INIT_VAR(attributes); PHALCON_CALL_METHOD_PARAMS_1(attributes, meta_data, "getattributes", this_ptr); if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(attribute); if (phalcon_isset_property_zval(this_ptr, attribute TSRMLS_CC)) { PHALCON_OBS_NVAR(value); phalcon_read_property_zval(&value, this_ptr, attribute, PH_NOISY_CC); phalcon_array_update_zval(&data, attribute, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_zval(&data, attribute, &null_value, PH_COPY | PH_SEPARATE TSRMLS_CC); } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(data); } /** * Enables/disables options in the ORM * * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model, setup){ zval *options, *disable_events, *virtual_foreign_keys; zval *column_renaming, *not_null_validations; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &options) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(options) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Options must be an array"); return; } /** * Enables/Disables globally the internal events */ if (phalcon_array_isset_string(options, SS("events"))) { PHALCON_OBS_VAR(disable_events); phalcon_array_fetch_string(&disable_events, options, SL("events"), PH_NOISY_CC); PHALCON_GLOBAL(orm).events = zend_is_true(disable_events); } /** * Enables/Disables virtual foreign keys */ if (phalcon_array_isset_string(options, SS("virtualForeignKeys"))) { PHALCON_OBS_VAR(virtual_foreign_keys); phalcon_array_fetch_string(&virtual_foreign_keys, options, SL("virtualForeignKeys"), PH_NOISY_CC); PHALCON_GLOBAL(orm).virtual_foreign_keys = zend_is_true(virtual_foreign_keys); } /** * Enables/Disables column renaming */ if (phalcon_array_isset_string(options, SS("columnRenaming"))) { PHALCON_OBS_VAR(column_renaming); phalcon_array_fetch_string(&column_renaming, options, SL("columnRenaming"), PH_NOISY_CC); PHALCON_GLOBAL(orm).column_renaming = zend_is_true(column_renaming); } /** * Enables/Disables automatic not null validation */ if (phalcon_array_isset_string(options, SS("notNullValidations"))) { PHALCON_OBS_VAR(not_null_validations); phalcon_array_fetch_string(&not_null_validations, options, SL("notNullValidations"), PH_NOISY_CC); PHALCON_GLOBAL(orm).not_null_validations = zend_is_true(not_null_validations); } PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/kernel/operators.h
<filename>ext/kernel/operators.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ /** Strict comparing */ #define PHALCON_IS_LONG(op1, op2) phalcon_compare_strict_long(op1, op2 TSRMLS_CC) #define PHALCON_IS_STRING(op1, op2) phalcon_compare_strict_string(op1, op2, strlen(op2)) /** strict boolean comparison */ #define PHALCON_IS_FALSE(var) Z_TYPE_P(var) == IS_BOOL && !Z_BVAL_P(var) #define PHALCON_IS_TRUE(var) Z_TYPE_P(var) == IS_BOOL && Z_BVAL_P(var) #define PHALCON_IS_NOT_FALSE(var) Z_TYPE_P(var) != IS_BOOL || (Z_TYPE_P(var) == IS_BOOL && Z_BVAL_P(var)) #define PHALCON_IS_NOT_TRUE(var) Z_TYPE_P(var) != IS_BOOL || (Z_TYPE_P(var) == IS_BOOL && !Z_BVAL_P(var)) /** SQL null empty **/ #define PHALCON_IS_EMPTY(var) Z_TYPE_P(var) == IS_NULL || (Z_TYPE_P(var) == IS_STRING && !Z_STRLEN_P(var)) #define PHALCON_IS_NOT_EMPTY(var) !(Z_TYPE_P(var) == IS_NULL || (Z_TYPE_P(var) == IS_STRING && !Z_STRLEN_P(var))) /** Is scalar */ #define PHALCON_IS_SCALAR(var) Z_TYPE_P(var) == IS_NULL || Z_TYPE_P(var) == IS_ARRAY || Z_TYPE_P(var) == IS_OBJECT || Z_TYPE_P(var) == IS_RESOURCE #define PHALCON_IS_NOT_SCALAR(var) !(Z_TYPE_P(var) == IS_NULL || Z_TYPE_P(var) == IS_ARRAY || Z_TYPE_P(var) == IS_OBJECT || Z_TYPE_P(var) == IS_RESOURCE) /** Equals/Identical */ #define PHALCON_IS_EQUAL(op1, op2) phalcon_is_equal(op1, op2 TSRMLS_CC) #define PHALCON_IS_IDENTICAL(op1, op2) phalcon_is_identical(op1, op2 TSRMLS_CC) /** Operator functions */ extern int phalcon_add_function(zval *result, zval *op1, zval *op2 TSRMLS_DC); extern int phalcon_and_function(zval *result, zval *left, zval *right); extern void phalcon_concat_self(zval **left, zval *right TSRMLS_DC); extern void phalcon_concat_self_str(zval **left, char *right, int right_length TSRMLS_DC); /** Strict comparing */ extern int phalcon_compare_strict_string(zval *op1, char *op2, int op2_length); extern int phalcon_compare_strict_long(zval *op1, long op2 TSRMLS_DC); extern int phalcon_is_smaller_strict_long(zval *op1, long op2 TSRMLS_DC); extern int phalcon_is_smaller_or_equal_strict_long(zval *op1, long op2 TSRMLS_DC); extern void phalcon_cast(zval *result, zval *var, zend_uint type); extern long phalcon_get_intval(zval *op); extern int phalcon_is_numeric(zval *op); extern int phalcon_is_equal(zval *op1, zval *op2 TSRMLS_DC); extern int phalcon_is_identical(zval *op1, zval *op2 TSRMLS_DC);
tmihalik/cphalcon
ext/mvc/model/metadata/files.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/file.h" #include "kernel/concat.h" #include "kernel/require.h" #include "kernel/operators.h" #include "kernel/exception.h" /** * Phalcon\Mvc\Model\MetaData\Files * * Stores model meta-data in PHP files. * *<code> * $metaData = new Phalcon\Mvc\Model\Metadata\Files(array( * 'metaDataDir' => 'app/cache/metadata/' * )); *</code> */ /** * Phalcon\Mvc\Model\MetaData\Files initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_MetaData_Files){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\Model\\MetaData, Files, mvc_model_metadata_files, "phalcon\\mvc\\model\\metadata", phalcon_mvc_model_metadata_files_method_entry, 0); zend_declare_property_string(phalcon_mvc_model_metadata_files_ce, SL("_metaDataDir"), "./", ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_model_metadata_files_ce TSRMLS_CC, 1, phalcon_mvc_model_metadatainterface_ce); return SUCCESS; } /** * Phalcon\Mvc\Model\MetaData\Files constructor * * @param array $options */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Files, __construct){ zval *options = NULL, *meta_data_dir, *empty_array; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } if (Z_TYPE_P(options) == IS_ARRAY) { if (phalcon_array_isset_string(options, SS("metaDataDir"))) { PHALCON_OBS_VAR(meta_data_dir); phalcon_array_fetch_string(&meta_data_dir, options, SL("metaDataDir"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_metaDataDir"), meta_data_dir TSRMLS_CC); } } PHALCON_INIT_VAR(empty_array); array_init(empty_array); phalcon_update_property_zval(this_ptr, SL("_metaData"), empty_array TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Reads meta-data from files * * @param string $key * @return array */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Files, read){ zval *key, *separator, *meta_data_dir, *virtual_key; zval *path, *data; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &key) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(separator); ZVAL_STRING(separator, "_", 1); PHALCON_OBS_VAR(meta_data_dir); phalcon_read_property(&meta_data_dir, this_ptr, SL("_metaDataDir"), PH_NOISY_CC); PHALCON_INIT_VAR(virtual_key); phalcon_prepare_virtual_path(virtual_key, key, separator TSRMLS_CC); PHALCON_INIT_VAR(path); PHALCON_CONCAT_VVS(path, meta_data_dir, key, ".php"); if (phalcon_file_exists(path TSRMLS_CC) == SUCCESS) { PHALCON_INIT_VAR(data); if (phalcon_require_ret(data, path TSRMLS_CC) == FAILURE) { return; } RETURN_CCTOR(data); } RETURN_MM_NULL(); } /** * Writes the meta-data to files * * @param string $key * @param array $data */ PHP_METHOD(Phalcon_Mvc_Model_MetaData_Files, write){ zval *key, *data, *separator, *meta_data_dir, *virtual_key; zval *path, *to_string, *export, *php_export, *status; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &key, &data) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(separator); ZVAL_STRING(separator, "_", 1); PHALCON_OBS_VAR(meta_data_dir); phalcon_read_property(&meta_data_dir, this_ptr, SL("_metaDataDir"), PH_NOISY_CC); PHALCON_INIT_VAR(virtual_key); phalcon_prepare_virtual_path(virtual_key, key, separator TSRMLS_CC); PHALCON_INIT_VAR(path); PHALCON_CONCAT_VVS(path, meta_data_dir, key, ".php"); PHALCON_INIT_VAR(to_string); ZVAL_BOOL(to_string, 1); PHALCON_INIT_VAR(export); PHALCON_CALL_FUNC_PARAMS_2(export, "var_export", data, to_string); PHALCON_INIT_VAR(php_export); PHALCON_CONCAT_SVS(php_export, "<?php return ", export, "; "); PHALCON_INIT_VAR(status); PHALCON_CALL_FUNC_PARAMS_2(status, "file_put_contents", path, php_export); if (PHALCON_IS_FALSE(status)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Meta-Data directory cannot be written"); return; } PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/db/adapter/pdo/mysql.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/string.h" #include "kernel/operators.h" /** * Phalcon\Db\Adapter\Pdo\Mysql * * Specific functions for the Mysql database system * <code> * * $config = array( * "host" => "192.168.0.11", * "dbname" => "blog", * "port" => 3306, * "username" => "sigma", * "password" => "<PASSWORD>" * ); * * $connection = new Phalcon\Db\Adapter\Pdo\Mysql($config); * * </code> */ /** * Phalcon\Db\Adapter\Pdo\Mysql initializer */ PHALCON_INIT_CLASS(Phalcon_Db_Adapter_Pdo_Mysql){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Db\\Adapter\\Pdo, Mysql, db_adapter_pdo_mysql, "phalcon\\db\\adapter\\pdo", phalcon_db_adapter_pdo_mysql_method_entry, 0); zend_declare_property_string(phalcon_db_adapter_pdo_mysql_ce, SL("_type"), "mysql", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(phalcon_db_adapter_pdo_mysql_ce, SL("_dialectType"), "mysql", ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_db_adapter_pdo_mysql_ce TSRMLS_CC, 1, phalcon_db_adapterinterface_ce); return SUCCESS; } /** * Escapes a column/table/schema name * * @param string $identifier * @return string */ PHP_METHOD(Phalcon_Db_Adapter_Pdo_Mysql, escapeIdentifier){ zval *identifier, *domain, *name, *escaped = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &identifier) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(identifier) == IS_ARRAY) { PHALCON_OBS_VAR(domain); phalcon_array_fetch_long(&domain, identifier, 0, PH_NOISY_CC); PHALCON_OBS_VAR(name); phalcon_array_fetch_long(&name, identifier, 1, PH_NOISY_CC); if (PHALCON_GLOBAL(db).escape_identifiers) { PHALCON_INIT_VAR(escaped); PHALCON_CONCAT_SVSVS(escaped, "`", domain, "`.`", name, "`"); } else { PHALCON_INIT_NVAR(escaped); PHALCON_CONCAT_VSV(escaped, domain, ".", name); } RETURN_CTOR(escaped); } if (PHALCON_GLOBAL(db).escape_identifiers) { PHALCON_INIT_NVAR(escaped); PHALCON_CONCAT_SVS(escaped, "`", identifier, "`"); RETURN_CTOR(escaped); } RETURN_CCTOR(identifier); } /** * Returns an array of Phalcon\Db\Column objects describing a table * * <code> * print_r($connection->describeColumns("posts")); ?> * </code> * * @param string $table * @param string $schema * @return Phalcon\Db\Column[] */ PHP_METHOD(Phalcon_Db_Adapter_Pdo_Mysql, describeColumns){ zval *table, *schema = NULL, *columns, *dialect, *sql, *fetch_assoc; zval *describe, *old_column = NULL, *size_pattern, *field = NULL; zval *definition = NULL, *column_type = NULL, *matches = NULL, *pos = NULL; zval *match_one = NULL, *attribute = NULL, *column_name = NULL, *column = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &table, &schema) == FAILURE) { RETURN_MM_NULL(); } if (!schema) { PHALCON_INIT_VAR(schema); } PHALCON_INIT_VAR(columns); array_init(columns); PHALCON_OBS_VAR(dialect); phalcon_read_property(&dialect, this_ptr, SL("_dialect"), PH_NOISY_CC); PHALCON_INIT_VAR(sql); PHALCON_CALL_METHOD_PARAMS_2(sql, dialect, "describecolumns", table, schema); PHALCON_INIT_VAR(fetch_assoc); phalcon_get_class_constant(fetch_assoc, phalcon_db_ce, SS("FETCH_ASSOC") TSRMLS_CC); PHALCON_INIT_VAR(describe); PHALCON_CALL_METHOD_PARAMS_2(describe, this_ptr, "fetchall", sql, fetch_assoc); PHALCON_INIT_VAR(old_column); PHALCON_INIT_VAR(size_pattern); ZVAL_STRING(size_pattern, "#\\(([0-9]+)(,[0-9]+)*\\)#", 1); if (!phalcon_is_iterable(describe, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(field); PHALCON_INIT_NVAR(definition); array_init_size(definition, 1); add_assoc_long_ex(definition, SS("bindType"), 2); /** * By checking every column type we convert it to a Phalcon\Db\Column */ PHALCON_OBS_NVAR(column_type); phalcon_array_fetch_string(&column_type, field, SL("type"), PH_NOISY_CC); if (phalcon_memnstr_str(column_type, SL("int") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 0, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_long(&definition, SL("bindType"), 1, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("varchar") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 2, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("datetime") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 4, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("decimal") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 3, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_long(&definition, SL("bindType"), 32, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("char") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 5, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("date") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 1, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("text") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 6, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("float") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 7, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_bool(&definition, SL("isNumeric"), 1, PH_SEPARATE TSRMLS_CC); phalcon_array_update_string_long(&definition, SL("bindType"), 32, PH_SEPARATE TSRMLS_CC); } else { if (phalcon_memnstr_str(column_type, SL("enum") TSRMLS_CC)) { phalcon_array_update_string_long(&definition, SL("type"), 5, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_string_long(&definition, SL("type"), 2, PH_SEPARATE TSRMLS_CC); } } } } } } } } } /** * If the column type has a parentheses we try to get the column size from it */ if (phalcon_memnstr_str(column_type, SL("(") TSRMLS_CC)) { PHALCON_INIT_NVAR(matches); array_init(matches); Z_SET_ISREF_P(matches); PHALCON_INIT_NVAR(pos); PHALCON_CALL_FUNC_PARAMS_3(pos, "preg_match", size_pattern, column_type, matches); Z_UNSET_ISREF_P(matches); if (zend_is_true(pos)) { if (phalcon_array_isset_long(matches, 1)) { PHALCON_OBS_NVAR(match_one); phalcon_array_fetch_long(&match_one, matches, 1, PH_NOISY_CC); phalcon_array_update_string(&definition, SL("size"), &match_one, PH_COPY | PH_SEPARATE TSRMLS_CC); } } } /** * Check if the column is unsigned, only MySQL support this */ if (phalcon_memnstr_str(column_type, SL("unsigned") TSRMLS_CC)) { phalcon_array_update_string_bool(&definition, SL("unsigned"), 1, PH_SEPARATE TSRMLS_CC); } if (!zend_is_true(old_column)) { phalcon_array_update_string_bool(&definition, SL("first"), 1, PH_SEPARATE TSRMLS_CC); } else { phalcon_array_update_string(&definition, SL("after"), &old_column, PH_COPY | PH_SEPARATE TSRMLS_CC); } /** * Check if the field is primary key */ PHALCON_OBS_NVAR(attribute); phalcon_array_fetch_string(&attribute, field, SL("key"), PH_NOISY_CC); if (PHALCON_IS_STRING(attribute, "PRI")) { phalcon_array_update_string_bool(&definition, SL("primary"), 1, PH_SEPARATE TSRMLS_CC); } /** * Check if the column allows null values */ PHALCON_OBS_NVAR(attribute); phalcon_array_fetch_string(&attribute, field, SL("null"), PH_NOISY_CC); if (PHALCON_IS_STRING(attribute, "NO")) { phalcon_array_update_string_bool(&definition, SL("notNull"), 1, PH_SEPARATE TSRMLS_CC); } /** * Check if the column is auto increment */ PHALCON_OBS_NVAR(attribute); phalcon_array_fetch_string(&attribute, field, SL("extra"), PH_NOISY_CC); if (PHALCON_IS_STRING(attribute, "auto_increment")) { phalcon_array_update_string_bool(&definition, SL("autoIncrement"), 1, PH_SEPARATE TSRMLS_CC); } PHALCON_OBS_NVAR(column_name); phalcon_array_fetch_string(&column_name, field, SL("field"), PH_NOISY_CC); PHALCON_INIT_NVAR(column); object_init_ex(column, phalcon_db_column_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(column, "__construct", column_name, definition); phalcon_array_append(&columns, column, PH_SEPARATE TSRMLS_CC); PHALCON_CPY_WRT(old_column, column_name); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(columns); }
tmihalik/cphalcon
ext/cache/frontend/base64.c
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/fcall.h" /** * Phalcon\Cache\Frontend\Base64 * * Allows to cache data converting/deconverting them to base64. * * This adapters uses the base64_encode/base64_decode PHP's functions * *<code> * * // Cache the files for 2 days using a Base64 frontend * $frontCache = new Phalcon\Cache\Frontend\Base64(array( * "lifetime" => 172800 * )); * * //Create a MongoDB cache * $cache = new Phalcon\Cache\Backend\Mongo($frontCache, array( * 'server' => "mongodb://localhost", * 'db' => 'caches', * 'collection' => 'images' * )); * * // Try to get cached image * $cacheKey = 'some-image.jpg.cache'; * $image = $cache->get($cacheKey); * if ($image === null) { * * // Store the image in the cache * $cache->save($cacheKey, file_put_contents('tmp-dir/some-image.jpg')); * } * * header('Content-Type: image/jpeg'); * echo $image; *</code> */ /** * Phalcon\Cache\Frontend\Base64 initializer */ PHALCON_INIT_CLASS(Phalcon_Cache_Frontend_Base64){ PHALCON_REGISTER_CLASS(Phalcon\\Cache\\Frontend, Base64, cache_frontend_base64, phalcon_cache_frontend_base64_method_entry, 0); zend_declare_property_null(phalcon_cache_frontend_base64_ce, SL("_frontendOptions"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_cache_frontend_base64_ce TSRMLS_CC, 1, phalcon_cache_frontendinterface_ce); return SUCCESS; } /** * Phalcon\Cache\Frontend\Base64 constructor * * @param array $frontendOptions */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, __construct){ zval *frontend_options = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &frontend_options) == FAILURE) { RETURN_MM_NULL(); } if (!frontend_options) { PHALCON_INIT_VAR(frontend_options); } phalcon_update_property_zval(this_ptr, SL("_frontendOptions"), frontend_options TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the cache lifetime * * @return integer */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, getLifetime){ zval *options, *lifetime; PHALCON_MM_GROW(); PHALCON_OBS_VAR(options); phalcon_read_property(&options, this_ptr, SL("_frontendOptions"), PH_NOISY_CC); if (Z_TYPE_P(options) == IS_ARRAY) { if (phalcon_array_isset_string(options, SS("lifetime"))) { PHALCON_OBS_VAR(lifetime); phalcon_array_fetch_string(&lifetime, options, SL("lifetime"), PH_NOISY_CC); RETURN_CCTOR(lifetime); } } PHALCON_MM_RESTORE(); RETURN_LONG(1); } /** * Check whether if frontend is buffering output * * @return boolean */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, isBuffering){ RETURN_FALSE; } /** * Starts output frontend. Actually, does nothing */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, start){ } /** * Returns output cached content * * @return string */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, getContent){ RETURN_NULL(); } /** * Stops output frontend */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, stop){ } /** * Serializes data before storing it * * @param mixed $data */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, beforeStore){ zval *data, *serialized; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(serialized); PHALCON_CALL_FUNC_PARAMS_1(serialized, "base64_encode", data); RETURN_CCTOR(serialized); } /** * Unserializes data after retrieving it * * @param mixed $data */ PHP_METHOD(Phalcon_Cache_Frontend_Base64, afterRetrieve){ zval *data, *unserialized; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(unserialized); PHALCON_CALL_FUNC_PARAMS_1(unserialized, "base64_decode", data); RETURN_CCTOR(unserialized); }
tmihalik/cphalcon
ext/tag/select.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/fcall.h" #include "kernel/operators.h" #include "kernel/concat.h" #include "kernel/exception.h" /** * Phalcon\Tag\Select * * Generates a SELECT html tag using a static array of values or a Phalcon\Mvc\Model resultset */ /** * Phalcon\Tag\Select initializer */ PHALCON_INIT_CLASS(Phalcon_Tag_Select){ PHALCON_REGISTER_CLASS(Phalcon\\Tag, Select, tag_select, phalcon_tag_select_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); return SUCCESS; } /** * Generates a SELECT tag * * @param array $parameters * @param array $data */ PHP_METHOD(Phalcon_Tag_Select, selectField){ zval *parameters, *data = NULL, *params = NULL, *eol, *id = NULL, *name, *value = NULL; zval *use_empty = NULL, *empty_value = NULL, *empty_text = NULL, *code; zval *avalue = NULL, *key = NULL, *close_option, *options = NULL, *using; zval *resultset_options, *array_options; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &parameters, &data) == FAILURE) { RETURN_MM_NULL(); } if (!data) { PHALCON_INIT_VAR(data); } if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_INIT_VAR(params); array_init_size(params, 2); phalcon_array_append(&params, parameters, PH_SEPARATE TSRMLS_CC); phalcon_array_append(&params, data, PH_SEPARATE TSRMLS_CC); } else { PHALCON_CPY_WRT(params, parameters); } PHALCON_INIT_VAR(eol); zend_get_constant(SL("PHP_EOL"), eol TSRMLS_CC); if (!phalcon_array_isset_long(params, 0)) { PHALCON_OBS_VAR(id); phalcon_array_fetch_string(&id, params, SL("id"), PH_NOISY_CC); phalcon_array_update_long(&params, 0, &id, PH_COPY | PH_SEPARATE TSRMLS_CC); } PHALCON_OBS_NVAR(id); phalcon_array_fetch_long(&id, params, 0, PH_NOISY_CC); if (!phalcon_array_isset_string(params, SS("name"))) { phalcon_array_update_string(&params, SL("name"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, params, SL("name"), PH_NOISY_CC); if (!zend_is_true(name)) { phalcon_array_update_string(&params, SL("name"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC); } } if (!phalcon_array_isset_string(params, SS("id"))) { phalcon_array_update_string(&params, SL("id"), &id, PH_COPY | PH_SEPARATE TSRMLS_CC); } if (!phalcon_array_isset_string(params, SS("value"))) { PHALCON_INIT_VAR(value); PHALCON_CALL_STATIC_PARAMS_2(value, "phalcon\\tag", "getvalue", id, params); } else { PHALCON_OBS_NVAR(value); phalcon_array_fetch_string(&value, params, SL("value"), PH_NOISY_CC); PHALCON_SEPARATE(params); phalcon_array_unset_string(params, SS("value")); } PHALCON_INIT_VAR(use_empty); ZVAL_BOOL(use_empty, 0); if (phalcon_array_isset_string(params, SS("useEmpty"))) { if (!phalcon_array_isset_string(params, SS("emptyValue"))) { PHALCON_INIT_VAR(empty_value); ZVAL_STRING(empty_value, "", 1); } else { PHALCON_OBS_NVAR(empty_value); phalcon_array_fetch_string(&empty_value, params, SL("emptyValue"), PH_NOISY_CC); PHALCON_SEPARATE(params); phalcon_array_unset_string(params, SS("emptyValue")); } if (!phalcon_array_isset_string(params, SS("emptyText"))) { PHALCON_INIT_VAR(empty_text); ZVAL_STRING(empty_text, "Choose...", 1); } else { PHALCON_OBS_NVAR(empty_text); phalcon_array_fetch_string(&empty_text, params, SL("emptyText"), PH_NOISY_CC); PHALCON_SEPARATE(params); phalcon_array_unset_string(params, SS("emptyText")); } PHALCON_OBS_NVAR(use_empty); phalcon_array_fetch_string(&use_empty, params, SL("useEmpty"), PH_NOISY_CC); PHALCON_SEPARATE(params); phalcon_array_unset_string(params, SS("useEmpty")); } PHALCON_INIT_VAR(code); ZVAL_STRING(code, "<select", 1); if (Z_TYPE_P(params) == IS_ARRAY) { if (!phalcon_is_iterable(params, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(avalue); if (Z_TYPE_P(key) != IS_LONG) { if (Z_TYPE_P(avalue) != IS_ARRAY) { PHALCON_SCONCAT_SVSVS(code, " ", key, "=\"", avalue, "\""); } } zend_hash_move_forward_ex(ah0, &hp0); } } PHALCON_SCONCAT_SV(code, ">", eol); PHALCON_INIT_VAR(close_option); PHALCON_CONCAT_SV(close_option, "</option>", eol); if (zend_is_true(use_empty)) { /** * Create an empty value */ PHALCON_SCONCAT_SVSVV(code, "\t<option value=\"", empty_value, "\">", empty_text, close_option); PHALCON_SEPARATE(params); phalcon_array_unset_string(params, SS("useEmpty")); } if (phalcon_array_isset_long(params, 1)) { PHALCON_OBS_VAR(options); phalcon_array_fetch_long(&options, params, 1, PH_NOISY_CC); } else { PHALCON_CPY_WRT(options, data); } if (Z_TYPE_P(options) == IS_OBJECT) { /** * The options is a resultset */ if (!phalcon_array_isset_string(params, SS("using"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_tag_exception_ce, "The 'using' parameter is required"); return; } else { PHALCON_OBS_VAR(using); phalcon_array_fetch_string(&using, params, SL("using"), PH_NOISY_CC); if (Z_TYPE_P(using) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_tag_exception_ce, "The 'using' parameter should be an Array"); return; } } /** * Create the SELECT's option from a resultset */ PHALCON_INIT_VAR(resultset_options); PHALCON_CALL_SELF_PARAMS_4(resultset_options, this_ptr, "_optionsfromresultset", options, using, value, close_option); phalcon_concat_self(&code, resultset_options TSRMLS_CC); } else { if (Z_TYPE_P(options) == IS_ARRAY) { /** * Create the SELECT's option from an array */ PHALCON_INIT_VAR(array_options); PHALCON_CALL_SELF_PARAMS_3(array_options, this_ptr, "_optionsfromarray", options, value, close_option); phalcon_concat_self(&code, array_options TSRMLS_CC); } else { PHALCON_THROW_EXCEPTION_STR(phalcon_tag_exception_ce, "Invalid data provided to SELECT helper"); return; } } phalcon_concat_self_str(&code, SL("</select>") TSRMLS_CC); RETURN_CTOR(code); } /** * Generate the OPTION tags based on a resulset * * @param Phalcon\Mvc\Model $resultset * @param array $using * @param mixed value * @param string $closeOption */ PHP_METHOD(Phalcon_Tag_Select, _optionsFromResultset){ zval *resultset, *using, *value, *close_option; zval *code, *using_zero = NULL, *using_one = NULL, *option = NULL, *option_value = NULL; zval *option_text = NULL; zval *r0 = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzz", &resultset, &using, &value, &close_option) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(code); ZVAL_STRING(code, "", 1); PHALCON_CALL_METHOD_NORETURN(resultset, "rewind"); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, resultset, "valid"); if (PHALCON_IS_NOT_FALSE(r0)) { } else { break; } PHALCON_OBS_NVAR(using_zero); phalcon_array_fetch_long(&using_zero, using, 0, PH_NOISY_CC); PHALCON_OBS_NVAR(using_one); phalcon_array_fetch_long(&using_one, using, 1, PH_NOISY_CC); /** * Get the current option */ PHALCON_INIT_NVAR(option); PHALCON_CALL_METHOD(option, resultset, "current"); /** * Read the value attribute from the model */ PHALCON_INIT_NVAR(option_value); PHALCON_CALL_METHOD_PARAMS_1(option_value, option, "readattribute", using_zero); /** * Read the text attribute from the model */ PHALCON_INIT_NVAR(option_text); PHALCON_CALL_METHOD_PARAMS_1(option_text, option, "readattribute", using_one); /** * If the value is equal to the option's value we mark it as selected */ if (PHALCON_IS_EQUAL(value, option_value)) { PHALCON_SCONCAT_SVSVV(code, "\t<option selected=\"selected\" value=\"", option_value, "\">", option_text, close_option); } else { PHALCON_SCONCAT_SVSVV(code, "\t<option value=\"", option_value, "\">", option_text, close_option); } PHALCON_CALL_METHOD_NORETURN(resultset, "next"); } RETURN_CTOR(code); } /** * Generate the OPTION tags based on an array * * @param Phalcon\Mvc\ModelInterface $resultset * @param array $using * @param mixed value * @param string $closeOption */ PHP_METHOD(Phalcon_Tag_Select, _optionsFromArray){ zval *data, *value, *close_option, *code, *option_text = NULL; zval *option_value = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &data, &value, &close_option) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(code); ZVAL_STRING(code, "", 1); if (!phalcon_is_iterable(data, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(option_value, ah0, hp0); PHALCON_GET_FOREACH_VALUE(option_text); if (PHALCON_IS_EQUAL(value, option_value)) { PHALCON_SCONCAT_SVSVV(code, "\t<option selected=\"selected\" value=\"", option_value, "\">", option_text, close_option); } else { PHALCON_SCONCAT_SVSVV(code, "\t<option value=\"", option_value, "\">", option_text, close_option); } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(code); }
tmihalik/cphalcon
ext/mvc/model/query/scanner.c
/* Generated by re2c 0.13.5 on Fri Jan 18 16:53:42 2013 */ // 1 "scanner.re" /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2012 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "scanner.h" #define YYCTYPE unsigned char #define YYCURSOR (s->start) #define YYLIMIT (s->end) #define YYMARKER q int phql_get_token(phql_scanner_state *s, phql_scanner_token *token) { char *q = YYCURSOR; int status = PHQL_SCANNER_RETCODE_IMPOSSIBLE; while (PHQL_SCANNER_RETCODE_IMPOSSIBLE == status) { // 45 "scanner.c" { YYCTYPE yych; yych = *YYCURSOR; switch (yych) { case 0x00: goto yy62; case '\t': case '\n': case '\r': case ' ': goto yy60; case '!': goto yy48; case '"': goto yy27; case '%': goto yy40; case '&': goto yy56; case '\'': goto yy28; case '(': goto yy44; case ')': goto yy46; case '*': goto yy36; case '+': goto yy32; case ',': goto yy42; case '-': goto yy34; case '.': goto yy4; case '/': goto yy38; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy2; case ':': goto yy8; case '<': goto yy50; case '=': goto yy54; case '>': goto yy52; case '?': goto yy6; case 'A': case 'a': goto yy14; case 'B': case 'b': goto yy19; case 'C': case 'c': goto yy26; case 'D': case 'd': goto yy12; case 'E': case 'K': case 'M': case 'P': case 'Q': case 'T': case 'X': case 'Y': case 'Z': case 'e': case 'k': case 'm': case 'p': case 'q': case 't': case 'x': case 'y': case 'z': goto yy30; case 'F': case 'f': goto yy13; case 'G': case 'g': goto yy20; case 'H': case 'h': goto yy21; case 'I': case 'i': goto yy15; case 'J': case 'j': goto yy24; case 'L': case 'l': goto yy22; case 'N': case 'n': goto yy23; case 'O': case 'o': goto yy18; case 'R': case 'r': goto yy25; case 'S': case 's': goto yy11; case 'U': case 'u': goto yy9; case 'V': case 'v': goto yy16; case 'W': case 'w': goto yy17; case '[': goto yy31; case '\\': goto yy29; case '|': goto yy58; default: goto yy64; } yy2: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '.': goto yy245; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy247; default: goto yy3; } yy3: // 46 "scanner.re" { token->opcode = PHQL_T_INTEGER; token->value = estrndup(q, YYCURSOR - q); token->len = YYCURSOR - q; q = YYCURSOR; return 0; } // 166 "scanner.c" yy4: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy242; default: goto yy5; } yy5: // 308 "scanner.re" { token->opcode = PHQL_T_DOT; return 0; } // 188 "scanner.c" yy6: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy239; default: goto yy7; } yy7: // 388 "scanner.re" { status = PHQL_SCANNER_RETCODE_ERR; break; } // 210 "scanner.c" yy8: yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy235; default: goto yy7; } yy9: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case 'P': case 'p': goto yy229; default: goto yy81; } yy10: // 266 "scanner.re" { token->opcode = PHQL_T_IDENTIFIER; token->value = estrndup(q, YYCURSOR - q); token->len = YYCURSOR - q; q = YYCURSOR; return 0; } // 295 "scanner.c" yy11: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy221; default: goto yy81; } yy12: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy204; case 'I': case 'i': goto yy205; default: goto yy81; } yy13: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy196; case 'U': case 'u': goto yy197; default: goto yy81; } yy14: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy189; case 'S': case 's': goto yy190; default: goto yy81; } yy15: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy173; case 'S': case 's': goto yy175; default: goto yy81; } yy16: yych = *++YYCURSOR; switch (yych) { case 'A': case 'a': goto yy167; default: goto yy81; } yy17: yych = *++YYCURSOR; switch (yych) { case 'H': case 'h': goto yy162; default: goto yy81; } yy18: yych = *++YYCURSOR; switch (yych) { case 'F': case 'f': goto yy143; case 'N': case 'n': goto yy144; case 'R': case 'r': goto yy146; case 'U': case 'u': goto yy148; default: goto yy81; } yy19: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy134; case 'Y': case 'y': goto yy135; default: goto yy81; } yy20: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy129; default: goto yy81; } yy21: yych = *++YYCURSOR; switch (yych) { case 'A': case 'a': goto yy123; default: goto yy81; } yy22: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy111; case 'I': case 'i': goto yy112; default: goto yy81; } yy23: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy104; case 'U': case 'u': goto yy105; default: goto yy81; } yy24: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy100; default: goto yy81; } yy25: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy95; default: goto yy81; } yy26: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy90; default: goto yy81; } yy27: yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy7; goto yy88; yy28: yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy7; goto yy83; yy29: yych = *++YYCURSOR; switch (yych) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy7; } yy30: yych = *++YYCURSOR; goto yy81; yy31: yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy75; default: goto yy7; } yy32: ++YYCURSOR; // 283 "scanner.re" { token->opcode = PHQL_T_ADD; return 0; } // 561 "scanner.c" yy34: ++YYCURSOR; // 288 "scanner.re" { token->opcode = PHQL_T_SUB; return 0; } // 569 "scanner.c" yy36: ++YYCURSOR; // 293 "scanner.re" { token->opcode = PHQL_T_MUL; return 0; } // 577 "scanner.c" yy38: ++YYCURSOR; // 298 "scanner.re" { token->opcode = PHQL_T_DIV; return 0; } // 585 "scanner.c" yy40: ++YYCURSOR; // 303 "scanner.re" { token->opcode = PHQL_T_MOD; return 0; } // 593 "scanner.c" yy42: ++YYCURSOR; // 313 "scanner.re" { token->opcode = PHQL_T_COMMA; return 0; } // 601 "scanner.c" yy44: ++YYCURSOR; // 318 "scanner.re" { token->opcode = PHQL_T_BRACKET_OPEN; return 0; } // 609 "scanner.c" yy46: ++YYCURSOR; // 323 "scanner.re" { token->opcode = PHQL_T_BRACKET_CLOSE; return 0; } // 617 "scanner.c" yy48: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '=': goto yy73; default: goto yy49; } yy49: // 353 "scanner.re" { token->opcode = PHQL_T_NOT; return 0; } // 630 "scanner.c" yy50: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '=': goto yy69; case '>': goto yy71; default: goto yy51; } yy51: // 358 "scanner.re" { token->opcode = PHQL_T_LESS; return 0; } // 644 "scanner.c" yy52: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '=': goto yy67; default: goto yy53; } yy53: // 363 "scanner.re" { token->opcode = PHQL_T_GREATER; return 0; } // 657 "scanner.c" yy54: ++YYCURSOR; // 348 "scanner.re" { token->opcode = PHQL_T_EQUALS; return 0; } // 665 "scanner.c" yy56: ++YYCURSOR; // 368 "scanner.re" { token->opcode = PHQL_T_BITWISE_AND; return 0; } // 673 "scanner.c" yy58: ++YYCURSOR; // 373 "scanner.re" { token->opcode = PHQL_T_BITWISE_OR; return 0; } // 681 "scanner.c" yy60: ++YYCURSOR; yych = *YYCURSOR; goto yy66; yy61: // 378 "scanner.re" { token->opcode = PHQL_T_IGNORE; return 0; } // 692 "scanner.c" yy62: ++YYCURSOR; // 383 "scanner.re" { status = PHQL_SCANNER_RETCODE_EOF; break; } // 700 "scanner.c" yy64: yych = *++YYCURSOR; goto yy7; yy65: ++YYCURSOR; yych = *YYCURSOR; yy66: switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy65; default: goto yy61; } yy67: ++YYCURSOR; // 343 "scanner.re" { token->opcode = PHQL_T_GREATEREQUAL; return 0; } // 722 "scanner.c" yy69: ++YYCURSOR; // 338 "scanner.re" { token->opcode = PHQL_T_LESSEQUAL; return 0; } // 730 "scanner.c" yy71: ++YYCURSOR; // 333 "scanner.re" { token->opcode = PHQL_T_NOTEQUALS; return 0; } // 738 "scanner.c" yy73: ++YYCURSOR; // 328 "scanner.re" { token->opcode = PHQL_T_NOTEQUALS; return 0; } // 746 "scanner.c" yy75: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy75; case ']': goto yy78; default: goto yy77; } yy77: YYCURSOR = YYMARKER; goto yy7; yy78: ++YYCURSOR; // 275 "scanner.re" { token->opcode = PHQL_T_IDENTIFIER; token->value = estrndup(q, YYCURSOR - q - 1); token->len = YYCURSOR - q - 1; q = YYCURSOR; return 0; } // 831 "scanner.c" yy80: ++YYCURSOR; yych = *YYCURSOR; yy81: switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy10; } yy82: ++YYCURSOR; yych = *YYCURSOR; yy83: switch (yych) { case 0x00: goto yy77; case '\'': goto yy85; case '\\': goto yy84; default: goto yy82; } yy84: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '\n': goto yy77; default: goto yy82; } yy85: ++YYCURSOR; // 257 "scanner.re" { token->opcode = PHQL_T_STRING; token->value = estrndup(q, YYCURSOR - q - 1); token->len = YYCURSOR - q - 1; q = YYCURSOR; return 0; } // 930 "scanner.c" yy87: ++YYCURSOR; yych = *YYCURSOR; yy88: switch (yych) { case 0x00: goto yy77; case '"': goto yy85; case '\\': goto yy89; default: goto yy87; } yy89: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '\n': goto yy77; default: goto yy87; } yy90: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy91; default: goto yy81; } yy91: yych = *++YYCURSOR; switch (yych) { case 'S': case 's': goto yy92; default: goto yy81; } yy92: yych = *++YYCURSOR; switch (yych) { case 'S': case 's': goto yy93; default: goto yy81; } yy93: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy94; } yy94: // 221 "scanner.re" { token->opcode = PHQL_T_CROSS; return 0; } // 1044 "scanner.c" yy95: yych = *++YYCURSOR; switch (yych) { case 'G': case 'g': goto yy96; default: goto yy81; } yy96: yych = *++YYCURSOR; switch (yych) { case 'H': case 'h': goto yy97; default: goto yy81; } yy97: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy98; default: goto yy81; } yy98: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy99; } yy99: // 216 "scanner.re" { token->opcode = PHQL_T_RIGHT; return 0; } // 1141 "scanner.c" yy100: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy101; default: goto yy81; } yy101: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy102; default: goto yy81; } yy102: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy103; } yy103: // 201 "scanner.re" { token->opcode = PHQL_T_JOIN; return 0; } // 1231 "scanner.c" yy104: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy109; default: goto yy81; } yy105: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy106; default: goto yy81; } yy106: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy107; default: goto yy81; } yy107: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy108; } yy108: // 241 "scanner.re" { token->opcode = PHQL_T_NULL; return 0; } // 1328 "scanner.c" yy109: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy110; } yy110: // 171 "scanner.re" { token->opcode = PHQL_T_NOT; return 0; } // 1404 "scanner.c" yy111: yych = *++YYCURSOR; switch (yych) { case 'F': case 'f': goto yy120; default: goto yy81; } yy112: yych = *++YYCURSOR; switch (yych) { case 'K': case 'k': goto yy114; case 'M': case 'm': goto yy113; default: goto yy81; } yy113: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy117; default: goto yy81; } yy114: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy115; default: goto yy81; } yy115: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy116; } yy116: // 186 "scanner.re" { token->opcode = PHQL_T_LIKE; return 0; } // 1510 "scanner.c" yy117: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy118; default: goto yy81; } yy118: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy119; } yy119: // 161 "scanner.re" { token->opcode = PHQL_T_LIMIT; return 0; } // 1593 "scanner.c" yy120: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy121; default: goto yy81; } yy121: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy122; } yy122: // 211 "scanner.re" { token->opcode = PHQL_T_LEFT; return 0; } // 1676 "scanner.c" yy123: yych = *++YYCURSOR; switch (yych) { case 'V': case 'v': goto yy124; default: goto yy81; } yy124: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy125; default: goto yy81; } yy125: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy126; default: goto yy81; } yy126: yych = *++YYCURSOR; switch (yych) { case 'G': case 'g': goto yy127; default: goto yy81; } yy127: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy128; } yy128: // 156 "scanner.re" { token->opcode = PHQL_T_HAVING; return 0; } // 1780 "scanner.c" yy129: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy130; default: goto yy81; } yy130: yych = *++YYCURSOR; switch (yych) { case 'U': case 'u': goto yy131; default: goto yy81; } yy131: yych = *++YYCURSOR; switch (yych) { case 'P': case 'p': goto yy132; default: goto yy81; } yy132: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy133; } yy133: // 151 "scanner.re" { token->opcode = PHQL_T_GROUP; return 0; } // 1877 "scanner.c" yy134: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy137; default: goto yy81; } yy135: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy136; } yy136: // 136 "scanner.re" { token->opcode = PHQL_T_BY; return 0; } // 1960 "scanner.c" yy137: yych = *++YYCURSOR; switch (yych) { case 'W': case 'w': goto yy138; default: goto yy81; } yy138: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy139; default: goto yy81; } yy139: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy140; default: goto yy81; } yy140: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy141; default: goto yy81; } yy141: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy142; } yy142: // 251 "scanner.re" { token->opcode = PHQL_T_BETWEEN; return 0; } // 2064 "scanner.c" yy143: yych = *++YYCURSOR; switch (yych) { case 'F': case 'f': goto yy157; default: goto yy81; } yy144: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy145; } yy145: // 196 "scanner.re" { token->opcode = PHQL_T_ON; return 0; } // 2147 "scanner.c" yy146: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; case 'D': case 'd': goto yy153; default: goto yy147; } yy147: // 181 "scanner.re" { token->opcode = PHQL_T_OR; return 0; } // 2223 "scanner.c" yy148: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy149; default: goto yy81; } yy149: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy150; default: goto yy81; } yy150: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy151; default: goto yy81; } yy151: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy152; } yy152: // 226 "scanner.re" { token->opcode = PHQL_T_OUTER; return 0; } // 2320 "scanner.c" yy153: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy154; default: goto yy81; } yy154: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy155; default: goto yy81; } yy155: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy156; } yy156: // 131 "scanner.re" { token->opcode = PHQL_T_ORDER; return 0; } // 2410 "scanner.c" yy157: yych = *++YYCURSOR; switch (yych) { case 'S': case 's': goto yy158; default: goto yy81; } yy158: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy159; default: goto yy81; } yy159: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy160; default: goto yy81; } yy160: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy161; } yy161: // 166 "scanner.re" { token->opcode = PHQL_T_OFFSET; return 0; } // 2507 "scanner.c" yy162: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy163; default: goto yy81; } yy163: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy164; default: goto yy81; } yy164: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy165; default: goto yy81; } yy165: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy166; } yy166: // 121 "scanner.re" { token->opcode = PHQL_T_WHERE; return 0; } // 2604 "scanner.c" yy167: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy168; default: goto yy81; } yy168: yych = *++YYCURSOR; switch (yych) { case 'U': case 'u': goto yy169; default: goto yy81; } yy169: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy170; default: goto yy81; } yy170: yych = *++YYCURSOR; switch (yych) { case 'S': case 's': goto yy171; default: goto yy81; } yy171: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy172; } yy172: // 116 "scanner.re" { token->opcode = PHQL_T_VALUES; return 0; } // 2708 "scanner.c" yy173: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'O': case 'P': case 'Q': case 'R': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'o': case 'p': case 'q': case 'r': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; case 'N': case 'n': goto yy179; case 'S': case 's': goto yy177; case 'T': case 't': goto yy178; default: goto yy174; } yy174: // 191 "scanner.re" { token->opcode = PHQL_T_IN; return 0; } // 2784 "scanner.c" yy175: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy176; } yy176: // 236 "scanner.re" { token->opcode = PHQL_T_IS; return 0; } // 2860 "scanner.c" yy177: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy185; default: goto yy81; } yy178: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy183; default: goto yy81; } yy179: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy180; default: goto yy81; } yy180: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy181; default: goto yy81; } yy181: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy182; } yy182: // 206 "scanner.re" { token->opcode = PHQL_T_INNER; return 0; } // 2964 "scanner.c" yy183: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy184; } yy184: // 111 "scanner.re" { token->opcode = PHQL_T_INTO; return 0; } // 3040 "scanner.c" yy185: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy186; default: goto yy81; } yy186: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy187; default: goto yy81; } yy187: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy188; } yy188: // 106 "scanner.re" { token->opcode = PHQL_T_INSERT; return 0; } // 3130 "scanner.c" yy189: yych = *++YYCURSOR; switch (yych) { case 'D': case 'd': goto yy194; default: goto yy81; } yy190: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; case 'C': case 'c': goto yy192; default: goto yy191; } yy191: // 101 "scanner.re" { token->opcode = PHQL_T_AS; return 0; } // 3213 "scanner.c" yy192: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy193; } yy193: // 141 "scanner.re" { token->opcode = PHQL_T_ASC; return 0; } // 3289 "scanner.c" yy194: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy195; } yy195: // 176 "scanner.re" { token->opcode = PHQL_T_AND; return 0; } // 3365 "scanner.c" yy196: yych = *++YYCURSOR; switch (yych) { case 'O': case 'o': goto yy201; default: goto yy81; } yy197: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy198; default: goto yy81; } yy198: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy199; default: goto yy81; } yy199: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy200; } yy200: // 231 "scanner.re" { token->opcode = PHQL_T_FULL; return 0; } // 3462 "scanner.c" yy201: yych = *++YYCURSOR; switch (yych) { case 'M': case 'm': goto yy202; default: goto yy81; } yy202: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy203; } yy203: // 96 "scanner.re" { token->opcode = PHQL_T_FROM; return 0; } // 3545 "scanner.c" yy204: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy213; case 'S': case 's': goto yy214; default: goto yy81; } yy205: yych = *++YYCURSOR; switch (yych) { case 'S': case 's': goto yy206; default: goto yy81; } yy206: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy207; default: goto yy81; } yy207: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy208; default: goto yy81; } yy208: yych = *++YYCURSOR; switch (yych) { case 'N': case 'n': goto yy209; default: goto yy81; } yy209: yych = *++YYCURSOR; switch (yych) { case 'C': case 'c': goto yy210; default: goto yy81; } yy210: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy211; default: goto yy81; } yy211: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy212; } yy212: // 246 "scanner.re" { token->opcode = PHQL_T_DISTINCT; return 0; } // 3672 "scanner.c" yy213: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy217; default: goto yy81; } yy214: yych = *++YYCURSOR; switch (yych) { case 'C': case 'c': goto yy215; default: goto yy81; } yy215: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy216; } yy216: // 146 "scanner.re" { token->opcode = PHQL_T_DESC; return 0; } // 3762 "scanner.c" yy217: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy218; default: goto yy81; } yy218: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy219; default: goto yy81; } yy219: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy220; } yy220: // 91 "scanner.re" { token->opcode = PHQL_T_DELETE; return 0; } // 3852 "scanner.c" yy221: yych = *++YYCURSOR; switch (yych) { case 'L': case 'l': goto yy224; case 'T': case 't': goto yy222; default: goto yy81; } yy222: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy223; } yy223: // 86 "scanner.re" { token->opcode = PHQL_T_SET; return 0; } // 3937 "scanner.c" yy224: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy225; default: goto yy81; } yy225: yych = *++YYCURSOR; switch (yych) { case 'C': case 'c': goto yy226; default: goto yy81; } yy226: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy227; default: goto yy81; } yy227: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy228; } yy228: // 126 "scanner.re" { token->opcode = PHQL_T_SELECT; return 0; } // 4034 "scanner.c" yy229: yych = *++YYCURSOR; switch (yych) { case 'D': case 'd': goto yy230; default: goto yy81; } yy230: yych = *++YYCURSOR; switch (yych) { case 'A': case 'a': goto yy231; default: goto yy81; } yy231: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy232; default: goto yy81; } yy232: yych = *++YYCURSOR; switch (yych) { case 'E': case 'e': goto yy233; default: goto yy81; } yy233: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '\\': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy80; default: goto yy234; } yy234: // 81 "scanner.re" { token->opcode = PHQL_T_UPDATE; return 0; } // 4138 "scanner.c" yy235: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy235; case ':': goto yy237; default: goto yy77; } yy237: ++YYCURSOR; // 73 "scanner.re" { token->opcode = PHQL_T_SPLACEHOLDER; token->value = estrndup(q, YYCURSOR - q - 1); token->len = YYCURSOR - q - 1; q = YYCURSOR; return 0; } // 4219 "scanner.c" yy239: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy239; default: goto yy241; } yy241: // 64 "scanner.re" { token->opcode = PHQL_T_NPLACEHOLDER; token->value = estrndup(q, YYCURSOR - q); token->len = YYCURSOR - q; q = YYCURSOR; return 0; } // 4245 "scanner.c" yy242: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy242; default: goto yy244; } yy244: // 55 "scanner.re" { token->opcode = PHQL_T_DOUBLE; token->value = estrndup(q, YYCURSOR - q); token->len = YYCURSOR - q; q = YYCURSOR; return 0; } // 4271 "scanner.c" yy245: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy245; default: goto yy244; } yy247: ++YYCURSOR; yych = *YYCURSOR; switch (yych) { case '.': goto yy245; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy247; default: goto yy3; } } // 393 "scanner.re" } return status; }
tmihalik/cphalcon
ext/mvc/model/criteria.c
<reponame>tmihalik/cphalcon<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/concat.h" #include "kernel/operators.h" #include "kernel/file.h" #include "kernel/fcall.h" #include "kernel/string.h" /** * Phalcon\Mvc\Model\Criteria * * This class allows to build the array parameter required by Phalcon\Mvc\Model::find * and Phalcon\Mvc\Model::findFirst, using an object-oriented interfase */ /** * Phalcon\Mvc\Model\Criteria initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Criteria){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc\\Model, Criteria, mvc_model_criteria, phalcon_mvc_model_criteria_method_entry, 0); zend_declare_property_null(phalcon_mvc_model_criteria_ce, SL("_model"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_criteria_ce, SL("_params"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_model_criteria_ce TSRMLS_CC, 2, phalcon_mvc_model_criteriainterface_ce, phalcon_di_injectionawareinterface_ce); return SUCCESS; } /** * Sets the DependencyInjector container * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, setDI){ zval *dependency_injector; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Dependency Injector is invalid"); return; } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("di"), dependency_injector TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the DependencyInjector container * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getDI){ zval *params, *dependency_injector; PHALCON_MM_GROW(); PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("di"))) { PHALCON_OBS_VAR(dependency_injector); phalcon_array_fetch_string(&dependency_injector, params, SL("di"), PH_NOISY_CC); RETURN_CCTOR(dependency_injector); } RETURN_MM_NULL(); } /** * Set a model on which the query will be executed * * @param string $modelName * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, setModelName){ zval *model_name; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &model_name) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(model_name) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Model name must be string"); return; } phalcon_update_property_zval(this_ptr, SL("_model"), model_name TSRMLS_CC); RETURN_THIS(); } /** * Returns an internal model name on which the criteria will be applied * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getModelName){ zval *model; PHALCON_MM_GROW(); PHALCON_OBS_VAR(model); phalcon_read_property(&model, this_ptr, SL("_model"), PH_NOISY_CC); RETURN_CCTOR(model); } /** * Adds the bind parameter to the criteria * * @param string $bindParams * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, bind){ zval *bind_params; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &bind_params) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(bind_params) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Bind parameters must be an Array"); return; } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("bind"), bind_params TSRMLS_CC); RETURN_THIS(); } /** * Adds the conditions parameter to the criteria * * @param string $conditions * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, where){ zval *conditions; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &conditions) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(conditions) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Conditions must be string"); return; } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("conditions"), conditions TSRMLS_CC); RETURN_THIS(); } /** * Appends a condition to the current conditions using an AND operator * * @param string $conditions * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, addWhere){ zval *conditions, *params, *current_conditions; zval *new_conditions = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &conditions) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(conditions) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Conditions must be string"); return; } PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_VAR(current_conditions); phalcon_array_fetch_string(&current_conditions, params, SL("conditions"), PH_NOISY_CC); PHALCON_INIT_VAR(new_conditions); PHALCON_CONCAT_SVSVS(new_conditions, "(", current_conditions, ") AND (", conditions, ")"); } else { PHALCON_CPY_WRT(new_conditions, conditions); } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("conditions"), new_conditions TSRMLS_CC); RETURN_THIS(); } /** * Appends a condition to the current conditions using an OR operator * * @param string $conditions * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, orWhere){ zval *conditions, *params, *current_conditions; zval *new_conditions = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &conditions) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(conditions) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Conditions must be string"); return; } PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_VAR(current_conditions); phalcon_array_fetch_string(&current_conditions, params, SL("conditions"), PH_NOISY_CC); PHALCON_INIT_VAR(new_conditions); PHALCON_CONCAT_SVSVS(new_conditions, "(", current_conditions, ") OR (", conditions, ")"); } else { PHALCON_CPY_WRT(new_conditions, conditions); } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("conditions"), new_conditions TSRMLS_CC); RETURN_THIS(); } /** * Adds the conditions parameter to the criteria * * @param string $conditions * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, conditions){ zval *conditions; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &conditions) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(conditions) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Conditions must be string"); return; } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("conditions"), conditions TSRMLS_CC); RETURN_THIS(); } /** * Adds the order-by parameter to the criteria * * @param string $orderColumns * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, order){ zval *order_columns; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &order_columns) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(order_columns) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Order columns must be string"); return; } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("order"), order_columns TSRMLS_CC); RETURN_THIS(); } /** * Adds the limit parameter to the criteria * * @param int $limit * @param int $offset * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, limit){ zval *limit, *offset = NULL, *limit_clause; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &limit, &offset) == FAILURE) { RETURN_MM_NULL(); } if (!offset) { PHALCON_INIT_VAR(offset); } if (!phalcon_is_numeric(limit)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Rows limit parameter must be integer"); return; } if (Z_TYPE_P(offset) == IS_NULL) { phalcon_update_property_array_string(this_ptr, SL("_params"), SS("limit"), limit TSRMLS_CC); } else { PHALCON_INIT_VAR(limit_clause); array_init_size(limit_clause, 2); phalcon_array_update_string(&limit_clause, SL("number"), &limit, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&limit_clause, SL("offset"), &offset, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_update_property_array_string(this_ptr, SL("_params"), SS("limit"), limit_clause TSRMLS_CC); } RETURN_THIS(); } /** * Adds the "for_update" parameter to the criteria * * @param boolean $forUpdate * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, forUpdate){ zval *for_update = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &for_update) == FAILURE) { RETURN_MM_NULL(); } if (!for_update) { PHALCON_INIT_VAR(for_update); ZVAL_BOOL(for_update, 1); } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("for_update"), for_update TSRMLS_CC); RETURN_THIS(); } /** * Adds the "shared_lock" parameter to the criteria * * @param boolean $sharedLock * @return Phalcon\Mvc\Model\Criteria */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, sharedLock){ zval *shared_lock = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &shared_lock) == FAILURE) { RETURN_MM_NULL(); } if (!shared_lock) { PHALCON_INIT_VAR(shared_lock); ZVAL_BOOL(shared_lock, 1); } phalcon_update_property_array_string(this_ptr, SL("_params"), SS("shared_lock"), shared_lock TSRMLS_CC); RETURN_THIS(); } /** * Returns the conditions parameter in the criteria * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getWhere){ zval *params, *conditions; PHALCON_MM_GROW(); PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("conditions"), PH_NOISY_CC); RETURN_CCTOR(conditions); } RETURN_MM_NULL(); } /** * Returns the conditions parameter in the criteria * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getConditions){ zval *params, *conditions; PHALCON_MM_GROW(); PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("conditions"), PH_NOISY_CC); RETURN_CCTOR(conditions); } RETURN_MM_NULL(); } /** * Returns the limit parameter in the criteria * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getLimit){ zval *params, *conditions; PHALCON_MM_GROW(); PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("limit"))) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("limit"), PH_NOISY_CC); RETURN_CCTOR(conditions); } RETURN_MM_NULL(); } /** * Returns the order parameter in the criteria * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getOrder){ zval *params, *conditions; PHALCON_MM_GROW(); PHALCON_OBS_VAR(params); phalcon_read_property(&params, this_ptr, SL("_params"), PH_NOISY_CC); if (phalcon_array_isset_string(params, SS("order"))) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("order"), PH_NOISY_CC); RETURN_CCTOR(conditions); } RETURN_MM_NULL(); } /** * Returns all the parameters defined in the criteria * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, getParams){ RETURN_MEMBER(this_ptr, "_params"); } /** * Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST * * @param Phalcon\DiInterface $dependencyInjector * @param string $modelName * @param array $data * @return static */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, fromInput){ zval *dependency_injector, *model_name, *data; zval *conditions, *service, *meta_data, *model; zval *data_types, *bind, *value = NULL, *field = NULL, *type = NULL, *condition = NULL; zval *value_pattern = NULL, *criteria, *join_conditions; HashTable *ah0; HashPosition hp0; zval **hd; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &dependency_injector, &model_name, &data) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(data) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Input data must be an Array"); return; } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the ORM services"); return; } PHALCON_INIT_VAR(conditions); array_init(conditions); if (phalcon_fast_count_ev(data TSRMLS_CC)) { PHALCON_INIT_VAR(service); ZVAL_STRING(service, "modelsMetadata", 1); PHALCON_INIT_VAR(meta_data); PHALCON_CALL_METHOD_PARAMS_1(meta_data, dependency_injector, "getshared", service); ce0 = phalcon_fetch_class(model_name TSRMLS_CC); PHALCON_INIT_VAR(model); object_init_ex(model, ce0); if (phalcon_has_constructor(model TSRMLS_CC)) { PHALCON_CALL_METHOD_NORETURN(model, "__construct"); } PHALCON_INIT_VAR(data_types); PHALCON_CALL_METHOD_PARAMS_1(data_types, meta_data, "getdatatypes", model); PHALCON_INIT_VAR(bind); array_init(bind); /** * We look for attributes in the array passed as data */ if (!phalcon_is_iterable(data, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(field, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (phalcon_array_isset(data_types, field)) { if (Z_TYPE_P(value) != IS_NULL) { if (!PHALCON_IS_STRING(value, "")) { PHALCON_OBS_NVAR(type); phalcon_array_fetch(&type, data_types, field, PH_NOISY_CC); if (PHALCON_IS_LONG(type, 2)) { /** * For varchar types we use LIKE operator */ PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VSVS(condition, field, " LIKE :", field, ":"); PHALCON_INIT_NVAR(value_pattern); PHALCON_CONCAT_SVS(value_pattern, "%", value, "%"); phalcon_array_update_zval(&bind, field, &value_pattern, PH_COPY | PH_SEPARATE TSRMLS_CC); } else { /** * For the rest of data types we use a plain = operator */ PHALCON_INIT_NVAR(condition); PHALCON_CONCAT_VSVS(condition, field, "=:", field, ":"); phalcon_array_update_zval(&bind, field, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } phalcon_array_append(&conditions, condition, PH_SEPARATE TSRMLS_CC); } } } zend_hash_move_forward_ex(ah0, &hp0); } } /** * Create an object instance and pass the paramaters to it */ PHALCON_INIT_VAR(criteria); object_init_ex(criteria, phalcon_mvc_model_criteria_ce); if (phalcon_fast_count_ev(conditions TSRMLS_CC)) { PHALCON_INIT_VAR(join_conditions); phalcon_fast_join_str(join_conditions, SL(" AND "), conditions TSRMLS_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(criteria, "where", join_conditions); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(criteria, "bind", bind); } RETURN_CTOR(criteria); } /** * Executes a find using the parameters built with the criteria * * @return Phalcon\Mvc\Model\ResultsetInterface */ PHP_METHOD(Phalcon_Mvc_Model_Criteria, execute){ zval *model, *params, *resultset; PHALCON_MM_GROW(); PHALCON_OBS_VAR(model); phalcon_read_property(&model, this_ptr, SL("_model"), PH_NOISY_CC); if (Z_TYPE_P(model) != IS_STRING) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Model name must be string"); return; } PHALCON_INIT_VAR(params); PHALCON_CALL_METHOD(params, this_ptr, "getparams"); PHALCON_INIT_VAR(resultset); PHALCON_CALL_STATIC_ZVAL_PARAMS_1(resultset, model, "find", params); RETURN_CCTOR(resultset); }
tmihalik/cphalcon
ext/diinterface.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "kernel/main.h" /** * Phalcon\DiInterface initializer */ PHALCON_INIT_CLASS(Phalcon_DiInterface){ PHALCON_REGISTER_INTERFACE_EX(Phalcon, DiInterface, diinterface, "arrayaccess", phalcon_diinterface_method_entry); return SUCCESS; } /** * Registers a service in the services container * * @param string $alias * @param mixed $definition * @param boolean $shared * @return Phalcon\DI\ServiceInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, set); /** * Registers an "always shared" service in the services container * * @param string $name * @param mixed $definition * @return Phalcon\DI\ServiceInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, setShared); /** * Removes a service in the services container * * @param string $alias */ PHALCON_DOC_METHOD(Phalcon_DiInterface, remove); /** * Attempts to register a service in the services container * Only is successful if a service hasn't been registered previously * with the same name * * @param string $alias * @param mixed $definition * @param boolean $shared * @return Phalcon\DI\ServiceInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, attempt); /** * Resolves the service based on its configuration * * @param string $alias * @param array $parameters * @return mixed */ PHALCON_DOC_METHOD(Phalcon_DiInterface, get); /** * Returns a shared service based on their configuration * * @param string $alias * @param array $parameters * @return mixed */ PHALCON_DOC_METHOD(Phalcon_DiInterface, getShared); /** * Sets a service using a raw Phalcon\DI\Service definition * * @param string $name * @param Phalcon\DI\ServiceInterface $rawDefinition * @return Phalcon\DI\ServiceInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, setRaw); /** * Returns a service definition without resolving * * @param string $name * @return mixed */ PHALCON_DOC_METHOD(Phalcon_DiInterface, getRaw); /** * Returns the corresponding Phalcon\Di\Service instance for a service * * @param string $name * @return Phalcon\DI\ServiceInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, getService); /** * Check whether the DI contains a service by a name * * @param string $alias * @return boolean */ PHALCON_DOC_METHOD(Phalcon_DiInterface, has); /** * Check whether the last service obtained via getShared produced a fresh instance or an existing one * * @return boolean */ PHALCON_DOC_METHOD(Phalcon_DiInterface, wasFreshInstance); /** * Return the services registered in the DI * * @return array */ PHALCON_DOC_METHOD(Phalcon_DiInterface, getServices); /** * Set a default dependency injection container to be obtained into static methods * * @param Phalcon\DiInterface $dependencyInjector */ PHALCON_DOC_METHOD(Phalcon_DiInterface, setDefault); /** * Return the last DI created * * @return Phalcon\DiInterface */ PHALCON_DOC_METHOD(Phalcon_DiInterface, getDefault); /** * Resets the internal default DI */ PHALCON_DOC_METHOD(Phalcon_DiInterface, reset);
tmihalik/cphalcon
ext/cache/backend.c
<reponame>tmihalik/cphalcon /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/array.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/operators.h" /** * Phalcon\Cache\Backend * * This class implements common functionality for backend adapters. A backend cache adapter may extend this class */ /** * Phalcon\Cache\Backend initializer */ PHALCON_INIT_CLASS(Phalcon_Cache_Backend){ PHALCON_REGISTER_CLASS(Phalcon\\Cache, Backend, cache_backend, phalcon_cache_backend_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_declare_property_null(phalcon_cache_backend_ce, SL("_frontend"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_cache_backend_ce, SL("_options"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(phalcon_cache_backend_ce, SL("_prefix"), "", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_string(phalcon_cache_backend_ce, SL("_lastKey"), "", ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_cache_backend_ce, SL("_fresh"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_cache_backend_ce, SL("_started"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } /** * Phalcon\Cache\Backend constructor * * @param Phalcon\Cache\FrontendInterface $frontend * @param array $options */ PHP_METHOD(Phalcon_Cache_Backend, __construct){ zval *frontend, *options = NULL, *prefix; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &frontend, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } if (Z_TYPE_P(frontend) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_cache_exception_ce, "Frontend must be an Object"); return; } /** * A common option is the prefix */ if (phalcon_array_isset_string(options, SS("prefix"))) { PHALCON_OBS_VAR(prefix); phalcon_array_fetch_string(&prefix, options, SL("prefix"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_prefix"), prefix TSRMLS_CC); } phalcon_update_property_zval(this_ptr, SL("_frontend"), frontend TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_options"), options TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Starts a cache. The $keyname allows to identify the created fragment * * @param int|string $keyName * @param long $lifetime * @return mixed */ PHP_METHOD(Phalcon_Cache_Backend, start){ zval *key_name, *lifetime = NULL, *existing_cache, *fresh = NULL; zval *frontend; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &key_name, &lifetime) == FAILURE) { RETURN_MM_NULL(); } if (!lifetime) { PHALCON_INIT_VAR(lifetime); } /** * Get the cache content verifying if it was expired */ PHALCON_INIT_VAR(existing_cache); PHALCON_CALL_METHOD_PARAMS_2(existing_cache, this_ptr, "get", key_name, lifetime); if (Z_TYPE_P(existing_cache) == IS_NULL) { PHALCON_INIT_VAR(fresh); ZVAL_BOOL(fresh, 1); PHALCON_OBS_VAR(frontend); phalcon_read_property(&frontend, this_ptr, SL("_frontend"), PH_NOISY_CC); PHALCON_CALL_METHOD_NORETURN(frontend, "start"); } else { PHALCON_INIT_NVAR(fresh); ZVAL_BOOL(fresh, 0); } phalcon_update_property_zval(this_ptr, SL("_fresh"), fresh TSRMLS_CC); phalcon_update_property_bool(this_ptr, SL("_started"), 1 TSRMLS_CC); RETURN_CCTOR(existing_cache); } /** * Stops the frontend without store any cached content * * @param boolean $stopBuffer */ PHP_METHOD(Phalcon_Cache_Backend, stop){ zval *stop_buffer = NULL, *frontend; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &stop_buffer) == FAILURE) { RETURN_MM_NULL(); } if (!stop_buffer) { PHALCON_INIT_VAR(stop_buffer); ZVAL_BOOL(stop_buffer, 1); } PHALCON_OBS_VAR(frontend); phalcon_read_property(&frontend, this_ptr, SL("_frontend"), PH_NOISY_CC); if (PHALCON_IS_TRUE(stop_buffer)) { PHALCON_CALL_METHOD_NORETURN(frontend, "stop"); } phalcon_update_property_bool(this_ptr, SL("_started"), 0 TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns front-end instance adapter related to the back-end * * @return mixed */ PHP_METHOD(Phalcon_Cache_Backend, getFrontend){ RETURN_MEMBER(this_ptr, "_frontend"); } /** * Returns the backend options * * @return array */ PHP_METHOD(Phalcon_Cache_Backend, getOptions){ RETURN_MEMBER(this_ptr, "_options"); } /** * Checks whether the last cache is fresh or cached * * @return boolean */ PHP_METHOD(Phalcon_Cache_Backend, isFresh){ RETURN_MEMBER(this_ptr, "_fresh"); } /** * Checks whether the cache has starting buffering or not * * @return boolean */ PHP_METHOD(Phalcon_Cache_Backend, isStarted){ RETURN_MEMBER(this_ptr, "_started"); } /** * Sets the last key used in the cache * * @param string $lastKey */ PHP_METHOD(Phalcon_Cache_Backend, setLastKey){ zval *last_key; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &last_key) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_lastKey"), last_key TSRMLS_CC); } /** * Gets the last key stored by the cache * * @return string */ PHP_METHOD(Phalcon_Cache_Backend, getLastKey){ RETURN_MEMBER(this_ptr, "_lastKey"); }
tmihalik/cphalcon
ext/mvc/model/query/builder.h
<filename>ext/mvc/model/query/builder.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_model_query_builder_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Query_Builder); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, __construct); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, setDI); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getDI); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, columns); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getColumns); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, from); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, addFrom); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getFrom); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, join); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, where); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, andWhere); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, orWhere); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getWhere); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, orderBy); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getOrderBy); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, having); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getHaving); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, limit); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getLimit); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, offset); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getOffset); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, groupBy); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getGroupBy); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getPhql); PHP_METHOD(Phalcon_Mvc_Model_Query_Builder, getQuery); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder___construct, 0, 0, 0) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_setdi, 0, 0, 1) ZEND_ARG_INFO(0, dependencyInjector) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_columns, 0, 0, 1) ZEND_ARG_INFO(0, columns) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_from, 0, 0, 1) ZEND_ARG_INFO(0, models) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_addfrom, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_join, 0, 0, 1) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, conditions) ZEND_ARG_INFO(0, alias) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_where, 0, 0, 1) ZEND_ARG_INFO(0, conditions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_andwhere, 0, 0, 1) ZEND_ARG_INFO(0, conditions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_orwhere, 0, 0, 1) ZEND_ARG_INFO(0, conditions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_orderby, 0, 0, 1) ZEND_ARG_INFO(0, orderBy) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_having, 0, 0, 1) ZEND_ARG_INFO(0, having) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_limit, 0, 0, 1) ZEND_ARG_INFO(0, limit) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_offset, 0, 0, 1) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_query_builder_groupby, 0, 0, 1) ZEND_ARG_INFO(0, group) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_model_query_builder_method_entry){ PHP_ME(Phalcon_Mvc_Model_Query_Builder, __construct, arginfo_phalcon_mvc_model_query_builder___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Mvc_Model_Query_Builder, setDI, arginfo_phalcon_mvc_model_query_builder_setdi, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getDI, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, columns, arginfo_phalcon_mvc_model_query_builder_columns, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getColumns, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, from, arginfo_phalcon_mvc_model_query_builder_from, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, addFrom, arginfo_phalcon_mvc_model_query_builder_addfrom, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getFrom, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, join, arginfo_phalcon_mvc_model_query_builder_join, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, where, arginfo_phalcon_mvc_model_query_builder_where, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, andWhere, arginfo_phalcon_mvc_model_query_builder_andwhere, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, orWhere, arginfo_phalcon_mvc_model_query_builder_orwhere, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getWhere, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, orderBy, arginfo_phalcon_mvc_model_query_builder_orderby, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getOrderBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, having, arginfo_phalcon_mvc_model_query_builder_having, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getHaving, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, limit, arginfo_phalcon_mvc_model_query_builder_limit, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getLimit, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, offset, arginfo_phalcon_mvc_model_query_builder_offset, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getOffset, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, groupBy, arginfo_phalcon_mvc_model_query_builder_groupby, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getGroupBy, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getPhql, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Query_Builder, getQuery, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/model/query/builderinterface.c
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "kernel/main.h" /** * Phalcon\Mvc\Model\Query\BuilderInterface initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Query_BuilderInterface){ PHALCON_REGISTER_INTERFACE(Phalcon\\Mvc\\Model\\Query, BuilderInterface, mvc_model_query_builderinterface, phalcon_mvc_model_query_builderinterface_method_entry); return SUCCESS; } /** * Phalcon\Mvc\Model\Query\Builder * * @param array $params */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, __construct); /** * Sets the columns to be queried * * @param string|array $columns * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, columns); /** * Return the columns to be queried * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getColumns); /** * Sets the models who makes part of the query * * @param string|array $models * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, from); /** * Add a model to take part of the query * * @param string $model * @param string $alias * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, addFrom); /** * Return the models who makes part of the query * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getFrom); /** * Adds a INNER join to the query * * @param string $model * @param string $conditions * @param string $alias * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, join); /** * Sets conditions for the query * * @param string $conditions * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, where); /** * Appends a condition to the current conditions using a AND operator * * @param string $conditions * @return Phalcon\Mvc\Model\Query\Builder */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, andWhere); /** * Appends a condition to the current conditions using a OR operator * * @param string $conditions * @return Phalcon\Mvc\Model\Query\Builder */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, orWhere); /** * Return the conditions for the query * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getWhere); /** * Sets a ORDER BY condition clause * * @param string $orderBy * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, orderBy); /** * Return the set ORDER BY clause * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getOrderBy); /** * Sets a HAVING condition clause * * @param string $having * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, having); /** * Returns the HAVING condition clause * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getHaving); /** * Sets a LIMIT clause * * @param int $limit * @param int $offset * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, limit); /** * Returns the current LIMIT clause * * @return string|array */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getLimit); /** * Sets a LIMIT clause * * @param string $group * @return Phalcon\Mvc\Model\Query\BuilderInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, groupBy); /** * Returns the GROUP BY clause * * @return string */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getGroupBy); /** * Returns a PHQL statement built based on the builder parameters * * @return string */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getPhql); /** * Returns the query built * * @return Phalcon\Mvc\Model\QueryInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Query_BuilderInterface, getQuery);
tmihalik/cphalcon
ext/db/adapter/pdo/postgresql.h
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_db_adapter_pdo_postgresql_ce; PHALCON_INIT_CLASS(Phalcon_Db_Adapter_Pdo_Postgresql); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Postgresql, connect); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Postgresql, describeColumns); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Postgresql, getDefaultIdValue); PHP_METHOD(Phalcon_Db_Adapter_Pdo_Postgresql, supportSequences); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_postgresql_connect, 0, 0, 0) ZEND_ARG_INFO(0, descriptor) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_postgresql_describecolumns, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_db_adapter_pdo_postgresql_method_entry){ PHP_ME(Phalcon_Db_Adapter_Pdo_Postgresql, connect, arginfo_phalcon_db_adapter_pdo_postgresql_connect, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Postgresql, describeColumns, arginfo_phalcon_db_adapter_pdo_postgresql_describecolumns, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Postgresql, getDefaultIdValue, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo_Postgresql, supportSequences, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/escaper.h
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_escaper_ce; PHALCON_INIT_CLASS(Phalcon_Escaper); PHP_METHOD(Phalcon_Escaper, setEnconding); PHP_METHOD(Phalcon_Escaper, getEncoding); PHP_METHOD(Phalcon_Escaper, setHtmlQuoteType); PHP_METHOD(Phalcon_Escaper, detectEncoding); PHP_METHOD(Phalcon_Escaper, normalizeEncoding); PHP_METHOD(Phalcon_Escaper, escapeHtml); PHP_METHOD(Phalcon_Escaper, escapeHtmlAttr); PHP_METHOD(Phalcon_Escaper, escapeCss); PHP_METHOD(Phalcon_Escaper, escapeJs); PHP_METHOD(Phalcon_Escaper, escapeUrl); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_setenconding, 0, 0, 1) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_sethtmlquotetype, 0, 0, 1) ZEND_ARG_INFO(0, quoteType) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_detectencoding, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_normalizeencoding, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_escapehtml, 0, 0, 1) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_escapehtmlattr, 0, 0, 1) ZEND_ARG_INFO(0, attribute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_escapecss, 0, 0, 1) ZEND_ARG_INFO(0, css) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_escapejs, 0, 0, 1) ZEND_ARG_INFO(0, js) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_escaper_escapeurl, 0, 0, 1) ZEND_ARG_INFO(0, url) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_escaper_method_entry){ PHP_ME(Phalcon_Escaper, setEnconding, arginfo_phalcon_escaper_setenconding, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, getEncoding, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, setHtmlQuoteType, arginfo_phalcon_escaper_sethtmlquotetype, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, detectEncoding, arginfo_phalcon_escaper_detectencoding, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, normalizeEncoding, arginfo_phalcon_escaper_normalizeencoding, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, escapeHtml, arginfo_phalcon_escaper_escapehtml, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, escapeHtmlAttr, arginfo_phalcon_escaper_escapehtmlattr, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, escapeCss, arginfo_phalcon_escaper_escapecss, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, escapeJs, arginfo_phalcon_escaper_escapejs, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Escaper, escapeUrl, arginfo_phalcon_escaper_escapeurl, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/collection.c
<reponame>tmihalik/cphalcon /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/exception.h" #include "kernel/object.h" #include "kernel/string.h" #include "kernel/array.h" #include "kernel/operators.h" #include "kernel/file.h" #include "kernel/concat.h" /** * Phalcon\Mvc\Collection * * This component implements a high level abstraction for NoSQL databases which * works with documents */ /** * Phalcon\Mvc\Collection initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Collection){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc, Collection, mvc_collection, phalcon_mvc_collection_method_entry, 0); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_modelsManager"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_source"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_mvc_collection_ce, SL("_operationMade"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_connection"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_errorMessages"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_collection_ce, SL("_reserved"), ZEND_ACC_PROTECTED|ZEND_ACC_STATIC TSRMLS_CC); zend_declare_property_bool(phalcon_mvc_collection_ce, SL("_disableEvents"), 0, ZEND_ACC_PROTECTED|ZEND_ACC_STATIC TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_collection_ce, SL("OP_NONE"), 0 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_collection_ce, SL("OP_CREATE"), 1 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_collection_ce, SL("OP_UPDATE"), 2 TSRMLS_CC); zend_declare_class_constant_long(phalcon_mvc_collection_ce, SL("OP_DELETE"), 3 TSRMLS_CC); zend_class_implements(phalcon_mvc_collection_ce TSRMLS_CC, 3, phalcon_mvc_collectioninterface_ce, phalcon_di_injectionawareinterface_ce, zend_ce_serializable); return SUCCESS; } /** * Phalcon\Mvc\Model constructor * * @param Phalcon\DiInterface $dependencyInjector * @param Phalcon\Mvc\Collection\ManagerInterface $modelsManager */ PHP_METHOD(Phalcon_Mvc_Collection, __construct){ zval *dependency_injector = NULL, *models_manager = NULL; zval *service_name; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &dependency_injector, &models_manager) == FAILURE) { RETURN_MM_NULL(); } if (!dependency_injector) { PHALCON_INIT_VAR(dependency_injector); } else { PHALCON_SEPARATE_PARAM(dependency_injector); } if (!models_manager) { PHALCON_INIT_VAR(models_manager); } else { PHALCON_SEPARATE_PARAM(models_manager); } /** * We use a default DI if the user doesn't define one */ if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_INIT_NVAR(dependency_injector); PHALCON_CALL_STATIC(dependency_injector, "phalcon\\di", "getdefault"); } if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ORM"); return; } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); /** * Inject the manager service from the DI */ if (Z_TYPE_P(models_manager) != IS_OBJECT) { PHALCON_INIT_VAR(service_name); ZVAL_STRING(service_name, "collectionManager", 1); PHALCON_INIT_NVAR(models_manager); PHALCON_CALL_METHOD_PARAMS_1(models_manager, dependency_injector, "getshared", service_name); if (Z_TYPE_P(models_manager) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The injected service 'modelsManager' is not valid"); return; } } /** * Update the models-manager */ phalcon_update_property_zval(this_ptr, SL("_modelsManager"), models_manager TSRMLS_CC); /** * The manager always initializes the object */ PHALCON_CALL_METHOD_PARAMS_1_NORETURN(models_manager, "initialize", this_ptr); PHALCON_MM_RESTORE(); } /** * Sets a value for the _id property, creates a MongoId object if needed * * @param mixed $id */ PHP_METHOD(Phalcon_Mvc_Collection, setId){ zval *id, *models_manager, *use_implicit_ids; zval *mongo_id = NULL; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &id) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(id) != IS_OBJECT) { PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Check if the model use implicit ids */ PHALCON_INIT_VAR(use_implicit_ids); PHALCON_CALL_METHOD_PARAMS_1(use_implicit_ids, models_manager, "isusingimplicitobjectids", this_ptr); if (zend_is_true(use_implicit_ids)) { ce0 = zend_fetch_class(SL("MongoId"), ZEND_FETCH_CLASS_AUTO TSRMLS_CC); PHALCON_INIT_VAR(mongo_id); object_init_ex(mongo_id, ce0); if (phalcon_has_constructor(mongo_id TSRMLS_CC)) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(mongo_id, "__construct", id); } } else { PHALCON_CPY_WRT(mongo_id, id); } } else { PHALCON_CPY_WRT(mongo_id, id); } phalcon_update_property_zval(this_ptr, SL("_id"), mongo_id TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the value of the _id property * * @return \MongoId */ PHP_METHOD(Phalcon_Mvc_Collection, getId){ RETURN_MEMBER(this_ptr, "_id"); } /** * Sets the dependency injection container * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_Collection, setDI){ zval *dependency_injector; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); } /** * Returns the dependency injection container * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Mvc_Collection, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Sets a custom events manager * * @param Phalcon\Events\ManagerInterface $eventsManager */ PHP_METHOD(Phalcon_Mvc_Collection, setEventsManager){ zval *events_manager, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &events_manager) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(models_manager, "setcustomeventsmanager", this_ptr, events_manager); PHALCON_MM_RESTORE(); } /** * Returns the custom events manager * * @return Phalcon\Events\ManagerInterface */ PHP_METHOD(Phalcon_Mvc_Collection, getEventsManager){ zval *models_manager, *events_manager; PHALCON_MM_GROW(); PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(events_manager); PHALCON_CALL_METHOD_PARAMS_1(events_manager, models_manager, "getcustomeventsmanager", this_ptr); RETURN_CCTOR(events_manager); } /** * Returns the models manager related to the entity instance * * @return Phalcon\Mvc\Model\ManagerInterface */ PHP_METHOD(Phalcon_Mvc_Collection, getModelsManager){ RETURN_MEMBER(this_ptr, "_modelsManager"); } /** * Returns an array with reserved properties that cannot be part of the insert/update * * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, getReservedAttributes){ zval *reserved = NULL; PHALCON_MM_GROW(); PHALCON_OBS_VAR(reserved); phalcon_read_static_property(&reserved, SL("phalcon\\mvc\\collection"), SL("_reserved") TSRMLS_CC); if (Z_TYPE_P(reserved) == IS_NULL) { PHALCON_INIT_NVAR(reserved); array_init_size(reserved, 5); add_assoc_bool_ex(reserved, SS("_connection"), 1); add_assoc_bool_ex(reserved, SS("_dependencyInjector"), 1); add_assoc_bool_ex(reserved, SS("_source"), 1); add_assoc_bool_ex(reserved, SS("_operationMade"), 1); add_assoc_bool_ex(reserved, SS("_errorMessages"), 1); phalcon_update_static_property(SL("phalcon\\mvc\\collection"), SL("_reserved"), reserved TSRMLS_CC); } RETURN_CCTOR(reserved); } /** * Sets if a model must use implicit objects ids * * @param boolean $useImplicitObjectIds */ PHP_METHOD(Phalcon_Mvc_Collection, useImplicitObjectIds){ zval *use_implicit_object_ids, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &use_implicit_object_ids) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(models_manager, "useimplicitobjectids", this_ptr, use_implicit_object_ids); PHALCON_MM_RESTORE(); } /** * Sets collection name which model should be mapped * * @param string $source * @return Phalcon\Mvc\Collection */ PHP_METHOD(Phalcon_Mvc_Collection, setSource){ zval *source; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &source) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_source"), source TSRMLS_CC); RETURN_THISW(); } /** * Returns collection name mapped in the model * * @return string */ PHP_METHOD(Phalcon_Mvc_Collection, getSource){ zval *source = NULL, *class_name; PHALCON_MM_GROW(); PHALCON_OBS_VAR(source); phalcon_read_property(&source, this_ptr, SL("_source"), PH_NOISY_CC); if (!zend_is_true(source)) { PHALCON_INIT_VAR(class_name); phalcon_get_class_ns(class_name, this_ptr, 0 TSRMLS_CC); PHALCON_INIT_NVAR(source); phalcon_uncamelize(source, class_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_source"), source TSRMLS_CC); } RETURN_CCTOR(source); } /** * Sets the DependencyInjection connection service name * * @param string $connectionService * @return Phalcon\Mvc\Model */ PHP_METHOD(Phalcon_Mvc_Collection, setConnectionService){ zval *connection_service, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &connection_service) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(models_manager, "setconnectionservice", this_ptr, connection_service); RETURN_THIS(); } /** * Returns DependencyInjection connection service * * @return string */ PHP_METHOD(Phalcon_Mvc_Collection, getConnectionService){ zval *models_manager, *connection_service; PHALCON_MM_GROW(); PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(connection_service); PHALCON_CALL_METHOD_PARAMS_1(connection_service, models_manager, "getconnectionservice", this_ptr); RETURN_CCTOR(connection_service); } /** * Retrieves a database connection * * @return \MongoDb */ PHP_METHOD(Phalcon_Mvc_Collection, getConnection){ zval *connection = NULL, *models_manager; PHALCON_MM_GROW(); PHALCON_OBS_VAR(connection); phalcon_read_property(&connection, this_ptr, SL("_connection"), PH_NOISY_CC); if (Z_TYPE_P(connection) != IS_OBJECT) { PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_NVAR(connection); PHALCON_CALL_METHOD_PARAMS_1(connection, models_manager, "getconnection", this_ptr); phalcon_update_property_zval(this_ptr, SL("_connection"), connection TSRMLS_CC); } RETURN_CCTOR(connection); } /** * Reads an attribute value by its name * * <code> * echo $robot->readAttribute('name'); * </code> * * @param string $attribute * @return mixed */ PHP_METHOD(Phalcon_Mvc_Collection, readAttribute){ zval *attribute, *attribute_value; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &attribute) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_isset_property_zval(this_ptr, attribute TSRMLS_CC)) { PHALCON_OBS_VAR(attribute_value); phalcon_read_property_zval(&attribute_value, this_ptr, attribute, PH_NOISY_CC); RETURN_CCTOR(attribute_value); } RETURN_MM_NULL(); } /** * Writes an attribute value by its name * * <code> * $robot->writeAttribute('name', 'Rosey'); * </code> * * @param string $attribute * @param mixed $value */ PHP_METHOD(Phalcon_Mvc_Collection, writeAttribute){ zval *attribute, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &attribute, &value) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval_zval(this_ptr, attribute, value TSRMLS_CC); } /** * Returns a cloned collection * * @param Phalcon\Mvc\Collection $collection * @param array $document * @return Phalcon\Mvc\Collection */ PHP_METHOD(Phalcon_Mvc_Collection, cloneResult){ zval *collection, *document, *cloned_collection; zval *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &collection, &document) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(collection) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "Invalid collection"); return; } if (Z_TYPE_P(document) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "Invalid document"); return; } PHALCON_INIT_VAR(cloned_collection); if (phalcon_clone(cloned_collection, collection TSRMLS_CC) == FAILURE) { return; } if (!phalcon_is_iterable(document, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(cloned_collection, "writeattribute", key, value); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CCTOR(cloned_collection); } /** * Returns a collection resultset * * @param array $params * @param Phalcon\Mvc\Collection $collection * @param \MongoDb $connection * @param boolean $unique * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, _getResultset){ zval *params, *collection, *connection, *unique; zval *source, *mongo_collection, *conditions = NULL; zval *documents_cursor, *limit, *sort = NULL, *document = NULL; zval *collection_cloned = NULL, *collections, *documents_array; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzz", &params, &collection, &connection, &unique) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, collection, "getsource"); PHALCON_INIT_VAR(mongo_collection); PHALCON_CALL_METHOD_PARAMS_1(mongo_collection, connection, "selectcollection", source); /** * Convert the string to an array */ if (phalcon_array_isset_long(params, 0)) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_long(&conditions, params, 0, PH_NOISY_CC); } else { if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_NVAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("conditions"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(conditions); array_init(conditions); } } /** * Perform the find */ PHALCON_INIT_VAR(documents_cursor); PHALCON_CALL_METHOD_PARAMS_1(documents_cursor, mongo_collection, "find", conditions); /** * Check if a 'limit' clause was defined */ if (phalcon_array_isset_string(params, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, params, SL("limit"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "limit", limit); } /** * Check if a 'sort' clause was defined */ if (phalcon_array_isset_string(params, SS("sort"))) { PHALCON_OBS_VAR(sort); phalcon_array_fetch_string(&sort, params, SL("sort"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "sort", sort); } /** * Check if a 'skip' clause was defined */ if (phalcon_array_isset_string(params, SS("skip"))) { PHALCON_OBS_NVAR(sort); phalcon_array_fetch_string(&sort, params, SL("skip"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "skip", sort); } if (PHALCON_IS_TRUE(unique)) { /** * Requesting a unique row */ PHALCON_CALL_METHOD_NORETURN(documents_cursor, "rewind"); PHALCON_INIT_VAR(document); PHALCON_CALL_METHOD(document, documents_cursor, "current"); if (Z_TYPE_P(document) == IS_ARRAY) { PHALCON_INIT_VAR(collection_cloned); PHALCON_CALL_SELF_PARAMS_2(collection_cloned, this_ptr, "cloneresult", collection, document); RETURN_CCTOR(collection_cloned); } RETURN_MM_FALSE; } /** * Requesting a complete resultset */ PHALCON_INIT_VAR(collections); array_init(collections); PHALCON_INIT_VAR(documents_array); PHALCON_CALL_FUNC_PARAMS_1(documents_array, "iterator_to_array", documents_cursor); if (!phalcon_is_iterable(documents_array, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(document); PHALCON_INIT_NVAR(collection_cloned); PHALCON_CALL_SELF_PARAMS_2(collection_cloned, this_ptr, "cloneresult", collection, document); phalcon_array_append(&collections, collection_cloned, PH_SEPARATE TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(collections); } /** * Perform a count over a resultset * * @param array $params * @param Phalcon\Mvc\Collection $collection * @param \MongoDb $connection * @return int */ PHP_METHOD(Phalcon_Mvc_Collection, _getGroupResultset){ zval *params, *collection, *connection, *source; zval *mongo_collection, *conditions = NULL, *simple = NULL; zval *documents_cursor, *limit, *sort = NULL, *group = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &params, &collection, &connection) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, collection, "getsource"); PHALCON_INIT_VAR(mongo_collection); PHALCON_CALL_METHOD_PARAMS_1(mongo_collection, connection, "selectcollection", source); /** * Convert the string to an array */ if (phalcon_array_isset_long(params, 0)) { PHALCON_OBS_VAR(conditions); phalcon_array_fetch_long(&conditions, params, 0, PH_NOISY_CC); } else { if (phalcon_array_isset_string(params, SS("conditions"))) { PHALCON_OBS_NVAR(conditions); phalcon_array_fetch_string(&conditions, params, SL("conditions"), PH_NOISY_CC); } else { PHALCON_INIT_NVAR(conditions); array_init(conditions); } } PHALCON_INIT_VAR(simple); ZVAL_BOOL(simple, 1); if (phalcon_array_isset_string(params, SS("limit"))) { ZVAL_BOOL(simple, 0); } else { if (phalcon_array_isset_string(params, SS("sort"))) { ZVAL_BOOL(simple, 0); } else { if (phalcon_array_isset_string(params, SS("skip"))) { ZVAL_BOOL(simple, 0); } } } if (PHALCON_IS_FALSE(simple)) { /** * Perform the find */ PHALCON_INIT_VAR(documents_cursor); PHALCON_CALL_METHOD_PARAMS_1(documents_cursor, mongo_collection, "find", conditions); /** * Check if a 'limit' clause was defined */ if (phalcon_array_isset_string(params, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, params, SL("limit"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "limit", limit); } /** * Check if a 'sort' clause was defined */ if (phalcon_array_isset_string(params, SS("sort"))) { PHALCON_OBS_VAR(sort); phalcon_array_fetch_string(&sort, params, SL("sort"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "sort", sort); } /** * Check if a 'skip' clause was defined */ if (phalcon_array_isset_string(params, SS("skip"))) { PHALCON_OBS_NVAR(sort); phalcon_array_fetch_string(&sort, params, SL("skip"), PH_NOISY_CC); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(documents_cursor, "skip", sort); } /** * Only 'count' is supported */ PHALCON_INIT_VAR(group); phalcon_fast_count(group, documents_cursor TSRMLS_CC); } PHALCON_INIT_NVAR(group); PHALCON_CALL_METHOD_PARAMS_1(group, mongo_collection, "count", conditions); RETURN_CCTOR(group); } /** * Executes internal hooks before save a document * * @param Phalcon\DiInterface $dependencyInjector * @param boolean $disableEvents * @param boolean $exists * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, _preSave){ zval *dependency_injector, *disable_events; zval *exists, *event_name = NULL, *status = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &dependency_injector, &disable_events, &exists) == FAILURE) { RETURN_MM_NULL(); } /** * Run Validation Callbacks Before */ if (!zend_is_true(disable_events)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "beforeValidation", 1); PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } if (!zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeValidationOnCreate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeValidationOnUpdate", 1); } PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } /** * Run validation */ PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "validation", 1); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { if (!zend_is_true(disable_events)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "onValidationFails", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } RETURN_MM_FALSE; } if (!zend_is_true(disable_events)) { /** * Run Validation Callbacks After */ if (!zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidationOnCreate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidationOnUpdate", 1); } PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterValidation", 1); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } /** * Run Before Callbacks */ PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeSave", 1); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } if (zend_is_true(exists)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeUpdate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "beforeCreate", 1); } PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } RETURN_MM_TRUE; } /** * Executes internal events after save a document * * @param boolean $disableEvents * @param boolean $success * @param boolean $exists * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, _postSave){ zval *disable_events, *success, *exists, *event_name = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &disable_events, &success, &exists) == FAILURE) { RETURN_MM_NULL(); } if (PHALCON_IS_TRUE(success)) { if (!zend_is_true(disable_events)) { if (PHALCON_IS_TRUE(exists)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "afterUpdate", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterCreate", 1); } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterSave", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } RETURN_CCTOR(success); } if (!zend_is_true(disable_events)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "notSave", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "_canceloperation", disable_events); RETURN_MM_FALSE; } /** * Executes validators on every validation call * *<code> *use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; * *class Subscriptors extends Phalcon\Mvc\Collection *{ * * public function validation() * { * $this->validate(new ExclusionIn(array( * 'field' => 'status', * 'domain' => array('A', 'I') * ))); * if ($this->validationHasFailed() == true) { * return false; * } * } * *} *</code> * * @param object $validator */ PHP_METHOD(Phalcon_Mvc_Collection, validate){ zval *validator, *status, *messages, *message = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &validator) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(validator) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Validator must be an Object"); return; } PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, validator, "validate", this_ptr); if (PHALCON_IS_FALSE(status)) { PHALCON_INIT_VAR(messages); PHALCON_CALL_METHOD(messages, validator, "getmessages"); if (!phalcon_is_iterable(messages, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_VALUE(message); phalcon_update_property_array_append(this_ptr, SL("_errorMessages"), message TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } } PHALCON_MM_RESTORE(); } /** * Check whether validation process has generated any messages * *<code> *use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn; * *class Subscriptors extends Phalcon\Mvc\Collection *{ * * public function validation() * { * $this->validate(new ExclusionIn(array( * 'field' => 'status', * 'domain' => array('A', 'I') * ))); * if ($this->validationHasFailed() == true) { * return false; * } * } * *} *</code> * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, validationHasFailed){ zval *error_messages; PHALCON_MM_GROW(); PHALCON_OBS_VAR(error_messages); phalcon_read_property(&error_messages, this_ptr, SL("_errorMessages"), PH_NOISY_CC); if (Z_TYPE_P(error_messages) == IS_ARRAY) { if (phalcon_fast_count_ev(error_messages TSRMLS_CC)) { RETURN_MM_TRUE; } } RETURN_MM_FALSE; } /** * Fires an internal event * * @param string $eventName * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, fireEvent){ zval *event_name, *models_manager, *success; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &event_name) == FAILURE) { RETURN_MM_NULL(); } /** * Check if there is a method with the same name of the event */ if (phalcon_method_exists(this_ptr, event_name TSRMLS_CC) == SUCCESS) { PHALCON_CALL_METHOD_NORETURN(this_ptr, Z_STRVAL_P(event_name)); } /** * Send a notification to the events manager */ PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_VAR(success); PHALCON_CALL_METHOD_PARAMS_2(success, models_manager, "notifyevent", event_name, this_ptr); RETURN_CCTOR(success); } /** * Fires an internal event that cancels the operation * * @param string $eventName * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, fireEventCancel){ zval *event_name, *status = NULL, *models_manager; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &event_name) == FAILURE) { RETURN_MM_NULL(); } /** * Check if there is a method with the same name of the event */ if (phalcon_method_exists(this_ptr, event_name TSRMLS_CC) == SUCCESS) { PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD(status, this_ptr, Z_STRVAL_P(event_name)); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } /** * Send a notification to the events manager */ PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, models_manager, "notifyevent", event_name, this_ptr); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } RETURN_MM_TRUE; } /** * Cancel the current operation * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, _cancelOperation){ zval *disable_events, *operation_made, *event_name = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &disable_events) == FAILURE) { RETURN_MM_NULL(); } if (!zend_is_true(disable_events)) { PHALCON_OBS_VAR(operation_made); phalcon_read_property(&operation_made, this_ptr, SL("_operationMade"), PH_NOISY_CC); if (PHALCON_IS_LONG(operation_made, 3)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "notDeleted", 1); } else { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "notSaved", 1); } PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } RETURN_MM_FALSE; } /** * Checks if the document exists in the collection * * @param \MongoCollection $collection */ PHP_METHOD(Phalcon_Mvc_Collection, _exists){ zval *collection, *id, *mongo_id = NULL, *models_manager; zval *use_implicit_ids, *parameters, *document_count; zval *zero, *exist; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &collection) == FAILURE) { RETURN_MM_NULL(); } if (phalcon_isset_property(this_ptr, SS("_id") TSRMLS_CC)) { PHALCON_OBS_VAR(id); phalcon_read_property(&id, this_ptr, SL("_id"), PH_NOISY_CC); if (Z_TYPE_P(id) == IS_OBJECT) { PHALCON_CPY_WRT(mongo_id, id); } else { PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Check if the model use implicit ids */ PHALCON_INIT_VAR(use_implicit_ids); PHALCON_CALL_METHOD_PARAMS_1(use_implicit_ids, models_manager, "isusingimplicitobjectids", this_ptr); if (zend_is_true(use_implicit_ids)) { ce0 = zend_fetch_class(SL("MongoId"), ZEND_FETCH_CLASS_AUTO TSRMLS_CC); PHALCON_INIT_VAR(mongo_id); object_init_ex(mongo_id, ce0); if (phalcon_has_constructor(mongo_id TSRMLS_CC)) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(mongo_id, "__construct", id); } phalcon_update_property_zval(this_ptr, SL("_id"), mongo_id TSRMLS_CC); } else { PHALCON_CPY_WRT(mongo_id, id); } } PHALCON_INIT_VAR(parameters); array_init_size(parameters, 1); phalcon_array_update_string(&parameters, SL("_id"), &mongo_id, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Perform the count using the function provided by the driver */ PHALCON_INIT_VAR(document_count); PHALCON_CALL_METHOD_PARAMS_1(document_count, collection, "count", parameters); PHALCON_INIT_VAR(zero); ZVAL_LONG(zero, 0); PHALCON_INIT_VAR(exist); is_smaller_function(exist, zero, document_count TSRMLS_CC); RETURN_NCTOR(exist); } RETURN_MM_FALSE; } /** * Returns all the validation messages * * <code> *$robot = new Robots(); *$robot->type = 'mechanical'; *$robot->name = '<NAME>'; *$robot->year = 1952; *if ($robot->save() == false) { * echo "Umh, We can't store robots right now "; * foreach ($robot->getMessages() as $message) { * echo $message; * } *} else { * echo "Great, a new robot was saved successfully!"; *} * </code> * * @return Phalcon\Mvc\Model\MessageInterface[] */ PHP_METHOD(Phalcon_Mvc_Collection, getMessages){ RETURN_MEMBER(this_ptr, "_errorMessages"); } /** * Appends a customized message on the validation process * *<code> * use \Phalcon\Mvc\Model\Message as Message; * * class Robots extends Phalcon\Mvc\Model * { * * public function beforeSave() * { * if (this->name == 'Peter') { * $message = new Message("Sorry, but a robot cannot be named Peter"); * $this->appendMessage($message); * } * } * } *</code> * * @param Phalcon\Mvc\Model\MessageInterface $message */ PHP_METHOD(Phalcon_Mvc_Collection, appendMessage){ zval *message, *type, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &message) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(message) != IS_OBJECT) { PHALCON_INIT_VAR(type); PHALCON_CALL_FUNC_PARAMS_1(type, "gettype", message); PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Invalid message format '", type, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_model_exception_ce, exception_message); return; } phalcon_update_property_array_append(this_ptr, SL("_errorMessages"), message TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Creates/Updates a collection based on the values in the atributes * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, save){ zval *dependency_injector, *source, *connection; zval *collection, *exists, *empty_array, *disable_events; zval *status = NULL, *data, *reserved, *properties, *value = NULL; zval *key = NULL, *success = NULL, *options, *ok, *id, *post_success; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ORM"); return; } PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); /** * Choose a collection according to the collection name */ PHALCON_INIT_VAR(collection); PHALCON_CALL_METHOD_PARAMS_1(collection, connection, "selectcollection", source); /** * Check the dirty state of the current operation to update the current operation */ PHALCON_INIT_VAR(exists); PHALCON_CALL_METHOD_PARAMS_1(exists, this_ptr, "_exists", collection); if (PHALCON_IS_FALSE(exists)) { phalcon_update_property_long(this_ptr, SL("_operationMade"), 1 TSRMLS_CC); } else { phalcon_update_property_long(this_ptr, SL("_operationMade"), 2 TSRMLS_CC); } PHALCON_INIT_VAR(empty_array); array_init(empty_array); /** * The messages added to the validator are reset here */ phalcon_update_property_zval(this_ptr, SL("_errorMessages"), empty_array TSRMLS_CC); PHALCON_OBS_VAR(disable_events); phalcon_read_static_property(&disable_events, SL("phalcon\\mvc\\collection"), SL("_disableEvents") TSRMLS_CC); /** * Execute the preSave hook */ PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_3(status, this_ptr, "_presave", dependency_injector, disable_events, exists); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } PHALCON_INIT_VAR(data); array_init(data); PHALCON_INIT_VAR(reserved); PHALCON_CALL_METHOD(reserved, this_ptr, "getreservedattributes"); PHALCON_INIT_VAR(properties); PHALCON_CALL_FUNC_PARAMS_1(properties, "get_object_vars", this_ptr); /** * We only assign values to the public properties */ if (!phalcon_is_iterable(properties, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (PHALCON_IS_STRING(key, "_id")) { if (Z_TYPE_P(value) != IS_NULL) { phalcon_array_update_zval(&data, key, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } } else { if (!phalcon_array_isset(reserved, key)) { phalcon_array_update_zval(&data, key, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } PHALCON_INIT_VAR(success); ZVAL_BOOL(success, 0); /** * We always use safe stores to get the success state */ PHALCON_INIT_VAR(options); array_init_size(options, 1); add_assoc_bool_ex(options, SS("safe"), 1); /** * Save the document */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, collection, "save", data, options); if (Z_TYPE_P(status) == IS_ARRAY) { if (phalcon_array_isset_string(status, SS("ok"))) { PHALCON_OBS_VAR(ok); phalcon_array_fetch_string(&ok, status, SL("ok"), PH_NOISY_CC); if (zend_is_true(ok)) { ZVAL_BOOL(success, 1); if (PHALCON_IS_FALSE(exists)) { if (phalcon_array_isset_string(data, SS("_id"))) { PHALCON_OBS_VAR(id); phalcon_array_fetch_string(&id, data, SL("_id"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_id"), id TSRMLS_CC); } } } } } else { ZVAL_BOOL(success, 0); } /** * Call the postSave hooks */ PHALCON_INIT_VAR(post_success); PHALCON_CALL_METHOD_PARAMS_3(post_success, this_ptr, "_postsave", disable_events, success, exists); RETURN_CCTOR(post_success); } /** * Find a document by its id (_id) * * @param string|\MongoId $id * @return Phalcon\Mvc\Collection */ PHP_METHOD(Phalcon_Mvc_Collection, findById){ zval *id, *class_name, *collection, *models_manager; zval *use_implicit_ids, *mongo_id = NULL, *conditions; zval *parameters, *result; zend_class_entry *ce0, *ce1; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &id) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(id) != IS_OBJECT) { PHALCON_INIT_VAR(class_name); phalcon_get_called_class(class_name TSRMLS_CC); ce0 = phalcon_fetch_class(class_name TSRMLS_CC); PHALCON_INIT_VAR(collection); object_init_ex(collection, ce0); if (phalcon_has_constructor(collection TSRMLS_CC)) { PHALCON_CALL_METHOD_NORETURN(collection, "__construct"); } PHALCON_INIT_VAR(models_manager); PHALCON_CALL_METHOD(models_manager, collection, "getmodelsmanager"); /** * Check if the model use implicit ids */ PHALCON_INIT_VAR(use_implicit_ids); PHALCON_CALL_METHOD_PARAMS_1(use_implicit_ids, models_manager, "isusingimplicitobjectids", collection); if (zend_is_true(use_implicit_ids)) { ce1 = zend_fetch_class(SL("MongoId"), ZEND_FETCH_CLASS_AUTO TSRMLS_CC); PHALCON_INIT_VAR(mongo_id); object_init_ex(mongo_id, ce1); if (phalcon_has_constructor(mongo_id TSRMLS_CC)) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(mongo_id, "__construct", id); } } else { PHALCON_CPY_WRT(mongo_id, id); } } else { PHALCON_CPY_WRT(mongo_id, id); } PHALCON_INIT_VAR(conditions); array_init_size(conditions, 1); phalcon_array_update_string(&conditions, SL("_id"), &mongo_id, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(parameters); array_init_size(parameters, 1); phalcon_array_append(&parameters, conditions, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(result); PHALCON_CALL_SELF_PARAMS_1(result, this_ptr, "findfirst", parameters); RETURN_CCTOR(result); } /** * Allows to query the first record that match the specified conditions * * <code> * * //What's the first robot in the robots table? * $robot = Robots::findFirst(); * echo "The robot name is ", $robot->name, "\n"; * * //What's the first mechanical robot in robots table? * $robot = Robots::findFirst(array( * array("type" => "mechanical") * )); * echo "The first mechanical robot name is ", $robot->name, "\n"; * * //Get first virtual robot ordered by name * $robot = Robots::findFirst(array( * array("type" => "mechanical"), * "order" => array("name" => 1) * )); * echo "The first virtual robot name is ", $robot->name, "\n"; * * </code> * * @param array $parameters * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, findFirst){ zval *parameters = NULL, *class_name, *collection, *connection; zval *unique, *resultset; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } if (Z_TYPE_P(parameters) != IS_NULL) { if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "Invalid parameters for findFirst"); return; } } PHALCON_INIT_VAR(class_name); phalcon_get_called_class(class_name TSRMLS_CC); ce0 = phalcon_fetch_class(class_name TSRMLS_CC); PHALCON_INIT_VAR(collection); object_init_ex(collection, ce0); if (phalcon_has_constructor(collection TSRMLS_CC)) { PHALCON_CALL_METHOD_NORETURN(collection, "__construct"); } PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, collection, "getconnection"); PHALCON_INIT_VAR(unique); ZVAL_BOOL(unique, 1); PHALCON_INIT_VAR(resultset); PHALCON_CALL_SELF_PARAMS_4(resultset, this_ptr, "_getresultset", parameters, collection, connection, unique); RETURN_CCTOR(resultset); } /** * Allows to query a set of records that match the specified conditions * * <code> * * //How many robots are there? * $robots = Robots::find(); * echo "There are ", count($robots), "\n"; * * //How many mechanical robots are there? * $robots = Robots::find(array( * array("type" => "mechanical") * )); * echo "There are ", count($robots), "\n"; * * //Get and print virtual robots ordered by name * $robots = Robots::findFirst(array( * array("type" => "virtual"), * "order" => array("name" => 1) * )); * foreach ($robots as $robot) { * echo $robot->name, "\n"; * } * * //Get first 100 virtual robots ordered by name * $robots = Robots::find(array( * array("type" => "virtual"), * "order" => array("name" => 1), * "limit" => 100 * )); * foreach ($robots as $robot) { * echo $robot->name, "\n"; * } * </code> * * @param array $parameters * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, find){ zval *parameters = NULL, *class_name, *collection, *connection; zval *unique, *resultset; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } if (Z_TYPE_P(parameters) != IS_NULL) { if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "Invalid parameters for find"); return; } } PHALCON_INIT_VAR(class_name); phalcon_get_called_class(class_name TSRMLS_CC); ce0 = phalcon_fetch_class(class_name TSRMLS_CC); PHALCON_INIT_VAR(collection); object_init_ex(collection, ce0); if (phalcon_has_constructor(collection TSRMLS_CC)) { PHALCON_CALL_METHOD_NORETURN(collection, "__construct"); } PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, collection, "getconnection"); PHALCON_INIT_VAR(unique); ZVAL_BOOL(unique, 0); PHALCON_INIT_VAR(resultset); PHALCON_CALL_SELF_PARAMS_4(resultset, this_ptr, "_getresultset", parameters, collection, connection, unique); RETURN_CCTOR(resultset); } /** * Perform a count over a collection * *<code> * echo 'There are ', Robots::count(), ' robots'; *</code> * * @param array $parameters * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, count){ zval *parameters = NULL, *class_name, *collection, *connection; zval *result; zend_class_entry *ce0; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &parameters) == FAILURE) { RETURN_MM_NULL(); } if (!parameters) { PHALCON_INIT_VAR(parameters); } if (Z_TYPE_P(parameters) != IS_NULL) { if (Z_TYPE_P(parameters) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "Invalid parameters for count"); return; } } PHALCON_INIT_VAR(class_name); phalcon_get_called_class(class_name TSRMLS_CC); ce0 = phalcon_fetch_class(class_name TSRMLS_CC); PHALCON_INIT_VAR(collection); object_init_ex(collection, ce0); if (phalcon_has_constructor(collection TSRMLS_CC)) { PHALCON_CALL_METHOD_NORETURN(collection, "__construct"); } PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, collection, "getconnection"); PHALCON_INIT_VAR(result); PHALCON_CALL_SELF_PARAMS_3(result, this_ptr, "_getgroupresultset", parameters, collection, connection); RETURN_CCTOR(result); } /** * Deletes a model instance. Returning true on success or false otherwise. * * <code> * * $robot = Robots::findFirst(); * $robot->delete(); * * foreach (Robots::find() as $robot) { * $robot->delete(); * } * </code> * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Collection, delete){ zval *disable_events, *event_name = NULL, *status = NULL, *id; zval *connection, *source, *collection, *mongo_id = NULL; zval *models_manager, *use_implicit_ids, *id_condition; zval *success = NULL, *options, *ok; zend_class_entry *ce0; PHALCON_MM_GROW(); if (!phalcon_isset_property(this_ptr, SS("_id") TSRMLS_CC)) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_collection_exception_ce, "The document cannot be deleted because it doesn't exist"); return; } PHALCON_OBS_VAR(disable_events); phalcon_read_static_property(&disable_events, SL("phalcon\\mvc\\collection"), SL("_disableEvents") TSRMLS_CC); if (!zend_is_true(disable_events)) { PHALCON_INIT_VAR(event_name); ZVAL_STRING(event_name, "beforeDelete", 1); PHALCON_INIT_VAR(status); PHALCON_CALL_METHOD_PARAMS_1(status, this_ptr, "fireeventcancel", event_name); if (PHALCON_IS_FALSE(status)) { RETURN_MM_FALSE; } } PHALCON_OBS_VAR(id); phalcon_read_property(&id, this_ptr, SL("_id"), PH_NOISY_CC); PHALCON_INIT_VAR(connection); PHALCON_CALL_METHOD(connection, this_ptr, "getconnection"); PHALCON_INIT_VAR(source); PHALCON_CALL_METHOD(source, this_ptr, "getsource"); /** * Get the \MongoCollection */ PHALCON_INIT_VAR(collection); PHALCON_CALL_METHOD_PARAMS_1(collection, connection, "selectcollection", source); if (Z_TYPE_P(id) == IS_OBJECT) { PHALCON_CPY_WRT(mongo_id, id); } else { PHALCON_OBS_VAR(models_manager); phalcon_read_property(&models_manager, this_ptr, SL("_modelsManager"), PH_NOISY_CC); /** * Is the collection using implicit object Ids? */ PHALCON_INIT_VAR(use_implicit_ids); PHALCON_CALL_METHOD_PARAMS_1(use_implicit_ids, models_manager, "isusingimplicitobjectids", this_ptr); if (zend_is_true(use_implicit_ids)) { ce0 = zend_fetch_class(SL("MongoId"), ZEND_FETCH_CLASS_AUTO TSRMLS_CC); PHALCON_INIT_VAR(mongo_id); object_init_ex(mongo_id, ce0); if (phalcon_has_constructor(mongo_id TSRMLS_CC)) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(mongo_id, "__construct", id); } } else { PHALCON_CPY_WRT(mongo_id, id); } } PHALCON_INIT_VAR(id_condition); array_init_size(id_condition, 1); phalcon_array_update_string(&id_condition, SL("_id"), &mongo_id, PH_COPY | PH_SEPARATE TSRMLS_CC); PHALCON_INIT_VAR(success); ZVAL_BOOL(success, 0); PHALCON_INIT_VAR(options); array_init_size(options, 1); add_assoc_bool_ex(options, SS("safe"), 1); /** * Remove the instance */ PHALCON_INIT_NVAR(status); PHALCON_CALL_METHOD_PARAMS_2(status, collection, "remove", id_condition, options); if (Z_TYPE_P(status) != IS_ARRAY) { RETURN_MM_FALSE; } /** * Check the operation status */ if (phalcon_array_isset_string(status, SS("ok"))) { PHALCON_OBS_VAR(ok); phalcon_array_fetch_string(&ok, status, SL("ok"), PH_NOISY_CC); if (zend_is_true(ok)) { ZVAL_BOOL(success, 1); if (!zend_is_true(disable_events)) { PHALCON_INIT_NVAR(event_name); ZVAL_STRING(event_name, "afterDelete", 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(this_ptr, "fireevent", event_name); } } } else { ZVAL_BOOL(success, 0); } RETURN_NCTOR(success); } /** * Returns the instance as an array representation * *<code> * print_r($robot->toArray()); *</code> * * @return array */ PHP_METHOD(Phalcon_Mvc_Collection, toArray){ zval *data, *reserved, *properties, *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_INIT_VAR(data); array_init(data); PHALCON_INIT_VAR(reserved); PHALCON_CALL_METHOD(reserved, this_ptr, "getreservedattributes"); /** * Get an array with the values of the object */ PHALCON_INIT_VAR(properties); PHALCON_CALL_FUNC_PARAMS_1(properties, "get_object_vars", this_ptr); /** * We only assign values to the public properties */ if (!phalcon_is_iterable(properties, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (PHALCON_IS_STRING(key, "_id")) { if (Z_TYPE_P(value) != IS_NULL) { phalcon_array_update_zval(&data, key, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } } else { if (!phalcon_array_isset(reserved, key)) { phalcon_array_update_zval(&data, key, &value, PH_COPY | PH_SEPARATE TSRMLS_CC); } } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_CTOR(data); } /** * Serializes the object ignoring connections or protected properties * * @return string */ PHP_METHOD(Phalcon_Mvc_Collection, serialize){ zval *data, *serialize; PHALCON_MM_GROW(); PHALCON_INIT_VAR(data); PHALCON_CALL_METHOD(data, this_ptr, "toarray"); /** * Use the standard serialize function to serialize the array data */ PHALCON_INIT_VAR(serialize); PHALCON_CALL_FUNC_PARAMS_1(serialize, "serialize", data); RETURN_CCTOR(serialize); } /** * Unserializes the object from a serialized string * * @param string $data */ PHP_METHOD(Phalcon_Mvc_Collection, unserialize){ zval *data, *attributes, *dependency_injector; zval *service, *manager, *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(data) == IS_STRING) { PHALCON_INIT_VAR(attributes); PHALCON_CALL_FUNC_PARAMS_1(attributes, "unserialize", data); if (Z_TYPE_P(attributes) == IS_ARRAY) { /** * Obtain the default DI */ PHALCON_INIT_VAR(dependency_injector); PHALCON_CALL_STATIC(dependency_injector, "phalcon\\di", "getdefault"); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "A dependency injector container is required to obtain the services related to the ODM"); return; } /** * Update the dependency injector */ phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); /** * Gets the default modelsManager service */ PHALCON_INIT_VAR(service); ZVAL_STRING(service, "collectionManager", 1); PHALCON_INIT_VAR(manager); PHALCON_CALL_METHOD_PARAMS_1(manager, dependency_injector, "getshared", service); if (Z_TYPE_P(manager) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "The injected service 'collectionManager' is not valid"); return; } /** * Update the models manager */ phalcon_update_property_zval(this_ptr, SL("_modelsManager"), manager TSRMLS_CC); /** * Update the objects attributes */ if (!phalcon_is_iterable(attributes, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); phalcon_update_property_zval_zval(this_ptr, key, value TSRMLS_CC); zend_hash_move_forward_ex(ah0, &hp0); } RETURN_MM_NULL(); } } PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid serialization data"); return; }
tmihalik/cphalcon
ext/http/response/cookies.h
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_http_response_cookies_ce; PHALCON_INIT_CLASS(Phalcon_Http_Response_Cookies); PHP_METHOD(Phalcon_Http_Response_Cookies, __construct); PHP_METHOD(Phalcon_Http_Response_Cookies, setDI); PHP_METHOD(Phalcon_Http_Response_Cookies, getDI); PHP_METHOD(Phalcon_Http_Response_Cookies, set); PHP_METHOD(Phalcon_Http_Response_Cookies, get); PHP_METHOD(Phalcon_Http_Response_Cookies, reset); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_response_cookies_setdi, 0, 0, 1) ZEND_ARG_INFO(0, dependencyInjector) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_response_cookies_set, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, expire) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_http_response_cookies_get, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_http_response_cookies_method_entry){ PHP_ME(Phalcon_Http_Response_Cookies, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Http_Response_Cookies, setDI, arginfo_phalcon_http_response_cookies_setdi, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Http_Response_Cookies, getDI, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Http_Response_Cookies, set, arginfo_phalcon_http_response_cookies_set, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Http_Response_Cookies, get, arginfo_phalcon_http_response_cookies_get, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Http_Response_Cookies, reset, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/model/query/parser.c
<filename>ext/mvc/model/query/parser.c /* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is include which follows the "include" declaration ** in the input file. */ #include <stdio.h> // 37 "parser.lemon" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "parser.h" #include "scanner.h" #include "phql.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/exception.h" static zval *phql_ret_literal_zval(int type, phql_parser_token *T) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (T) { add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); } return ret; } static zval *phql_ret_placeholder_zval(int type, phql_parser_token *T) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 2); add_assoc_long(ret, "type", type); add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); return ret; } static zval *phql_ret_qualified_name(phql_parser_token *A, phql_parser_token *B) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_QUALIFIED); if (B != NULL) { add_assoc_stringl(ret, "domain", A->token, A->token_len, 0); add_assoc_stringl(ret, "name", B->token, B->token_len, 0); efree(B); } else { add_assoc_stringl(ret, "name", A->token, A->token_len, 0); } efree(A); return ret; } static zval *phql_ret_select_statement(zval *S, zval *W, zval *O, zval *G, zval *H, zval *L) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_SELECT); add_assoc_zval(ret, "select", S); if (W != NULL) { add_assoc_zval(ret, "where", W); } if (O != NULL) { add_assoc_zval(ret, "orderBy", O); } if (G != NULL) { add_assoc_zval(ret, "groupBy", G); } if (H != NULL) { add_assoc_zval(ret, "having", H); } if (L != NULL) { add_assoc_zval(ret, "limit", L); } return ret; } static zval *phql_ret_select_clause(zval *columns, zval *tables, zval *join_list) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "columns", columns); add_assoc_zval(ret, "tables", tables); if (join_list) { add_assoc_zval(ret, "joins", join_list); } return ret; } static zval *phql_ret_order_item(zval *column, int sort){ zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "column", column); if (sort != 0 ) { add_assoc_long(ret, "sort", sort); } return ret; } static zval *phql_ret_limit_clause(phql_parser_token *L, phql_parser_token *O) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_stringl(ret, "number", L->token, L->token_len, 0); efree(L); if (O != NULL) { add_assoc_stringl(ret, "offset", O->token, O->token_len, 0); efree(O); } return ret; } static zval *phql_ret_insert_statement(zval *Q, zval *F, zval *V) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_INSERT); add_assoc_zval(ret, "qualifiedName", Q); if (F != NULL) { add_assoc_zval(ret, "fields", F); } add_assoc_zval(ret, "values", V); return ret; } static zval *phql_ret_update_statement(zval *U, zval *W, zval *L) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_UPDATE); add_assoc_zval(ret, "update", U); if (W != NULL) { add_assoc_zval(ret, "where", W); } if (L != NULL) { add_assoc_zval(ret, "limit", L); } return ret; } static zval *phql_ret_update_clause(zval *tables, zval *values) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 2); add_assoc_zval(ret, "tables", tables); add_assoc_zval(ret, "values", values); return ret; } static zval *phql_ret_update_item(zval *column, zval *expr) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 2); add_assoc_zval(ret, "column", column); add_assoc_zval(ret, "expr", expr); return ret; } static zval *phql_ret_delete_statement(zval *D, zval *W, zval *L) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_DELETE); add_assoc_zval(ret, "delete", D); if (W != NULL) { add_assoc_zval(ret, "where", W); } if (L != NULL) { add_assoc_zval(ret, "limit", L); } return ret; } static zval *phql_ret_delete_clause(zval *tables) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 1); add_assoc_zval(ret, "tables", tables); return ret; } static zval *phql_ret_zval_list(zval *list_left, zval *right_list) { zval *ret; HashPosition pos; HashTable *list; MAKE_STD_ZVAL(ret); array_init(ret); list = Z_ARRVAL_P(list_left); if (zend_hash_index_exists(list, 0)) { zend_hash_internal_pointer_reset_ex(list, &pos); for (;; zend_hash_move_forward_ex(list, &pos)) { zval ** item; if (zend_hash_get_current_data_ex(list, (void**)&item, &pos) == FAILURE) { break; } Z_ADDREF_PP(item); add_next_index_zval(ret, *item); } zval_ptr_dtor(&list_left); } else { add_next_index_zval(ret, list_left); } if (right_list) { add_next_index_zval(ret, right_list); } return ret; } static zval *phql_ret_column_item(int type, zval *column, phql_parser_token *identifier_column, phql_parser_token *alias) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (column) { add_assoc_zval(ret, "column", column); } if (identifier_column) { add_assoc_stringl(ret, "column", identifier_column->token, identifier_column->token_len, 0); efree(identifier_column); } if (alias) { add_assoc_stringl(ret, "alias", alias->token, alias->token_len, 0); efree(alias); } return ret; } static zval *phql_ret_assoc_name(zval *qualified_name, phql_parser_token *alias) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "qualifiedName", qualified_name); if (alias) { add_assoc_stringl(ret, "alias", alias->token, alias->token_len, 0); efree(alias); } return ret; } static zval *phql_ret_join_type(int type) { zval *ret; MAKE_STD_ZVAL(ret); ZVAL_LONG(ret, type); return ret; } static zval *phql_ret_join_item(zval *type, zval *qualified, zval *alias, zval *conditions) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "type", type); if (qualified) { add_assoc_zval(ret, "qualified", qualified); } if (alias) { add_assoc_zval(ret, "alias", alias); } if (conditions) { add_assoc_zval(ret, "conditions", conditions); } return ret; } static zval *phql_ret_expr(int type, zval *left, zval *right) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (left) { add_assoc_zval(ret, "left", left); } if (right) { add_assoc_zval(ret, "right", right); } return ret; } static zval *phql_ret_func_call(phql_parser_token *name, zval *arguments) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHQL_T_FCALL); add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); if (arguments) { add_assoc_zval(ret, "arguments", arguments); } return ret; } // 390 "parser.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** phql_TOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is phql_TOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. ** phql_ARG_SDECL A static variable declaration for the %extra_argument ** phql_ARG_PDECL A parameter declaration for the %extra_argument ** phql_ARG_STORE Code to store %extra_argument into yypParser ** phql_ARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ #define YYCODETYPE unsigned char #define YYNOCODE 104 #define YYACTIONTYPE unsigned short int #define phql_TOKENTYPE phql_parser_token* typedef union { phql_TOKENTYPE yy0; zval* yy10; int yy207; } YYMINORTYPE; #define YYSTACKDEPTH 100 #define phql_ARG_SDECL phql_parser_status *status; #define phql_ARG_PDECL ,phql_parser_status *status #define phql_ARG_FETCH phql_parser_status *status = yypParser->status #define phql_ARG_STORE yypParser->status = status #define YYNSTATE 237 #define YYNRULE 145 #define YYERRORSYMBOL 59 #define YYERRSYMDT yy207 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static YYACTIONTYPE yy_action[] = { /* 0 */ 83, 59, 61, 63, 65, 67, 69, 51, 53, 71, /* 10 */ 55, 57, 47, 45, 49, 43, 40, 79, 76, 237, /* 20 */ 73, 7, 125, 127, 189, 135, 187, 9, 83, 59, /* 30 */ 61, 63, 65, 67, 69, 51, 53, 71, 55, 57, /* 40 */ 47, 45, 49, 43, 40, 79, 76, 11, 73, 59, /* 50 */ 61, 63, 65, 67, 69, 51, 53, 71, 55, 57, /* 60 */ 47, 45, 49, 43, 40, 79, 76, 99, 73, 83, /* 70 */ 59, 61, 63, 65, 67, 69, 51, 53, 71, 55, /* 80 */ 57, 47, 45, 49, 43, 40, 79, 76, 90, 73, /* 90 */ 51, 53, 71, 55, 57, 47, 45, 49, 43, 40, /* 100 */ 79, 76, 92, 73, 89, 41, 142, 29, 93, 95, /* 110 */ 178, 144, 145, 86, 92, 79, 76, 41, 73, 238, /* 120 */ 93, 95, 25, 26, 31, 86, 172, 97, 107, 31, /* 130 */ 155, 156, 158, 160, 122, 164, 168, 101, 35, 97, /* 140 */ 17, 37, 104, 102, 103, 105, 106, 239, 30, 101, /* 150 */ 138, 119, 124, 123, 104, 102, 103, 105, 106, 182, /* 160 */ 8, 16, 41, 116, 191, 93, 95, 200, 185, 219, /* 170 */ 183, 234, 100, 41, 244, 196, 93, 95, 201, 33, /* 180 */ 18, 86, 29, 20, 97, 155, 156, 158, 160, 240, /* 190 */ 164, 168, 85, 241, 101, 97, 23, 34, 26, 104, /* 200 */ 102, 103, 105, 106, 128, 101, 130, 134, 140, 180, /* 210 */ 104, 102, 103, 105, 106, 242, 71, 55, 57, 47, /* 220 */ 45, 49, 43, 40, 79, 76, 10, 73, 55, 57, /* 230 */ 47, 45, 49, 43, 40, 79, 76, 81, 73, 143, /* 240 */ 144, 145, 383, 1, 2, 3, 4, 5, 6, 47, /* 250 */ 45, 49, 43, 40, 79, 76, 243, 73, 251, 136, /* 260 */ 21, 43, 40, 79, 76, 117, 73, 10, 78, 245, /* 270 */ 80, 213, 78, 100, 78, 13, 230, 100, 78, 100, /* 280 */ 200, 260, 249, 100, 203, 100, 139, 212, 207, 190, /* 290 */ 186, 201, 109, 85, 108, 100, 88, 85, 108, 85, /* 300 */ 91, 21, 113, 85, 108, 85, 117, 336, 10, 246, /* 310 */ 181, 186, 262, 200, 21, 85, 100, 22, 100, 247, /* 320 */ 38, 10, 228, 39, 199, 115, 21, 100, 100, 337, /* 330 */ 100, 12, 38, 10, 10, 15, 85, 42, 85, 227, /* 340 */ 44, 46, 100, 74, 48, 100, 100, 85, 85, 100, /* 350 */ 85, 50, 111, 52, 21, 122, 100, 21, 100, 338, /* 360 */ 14, 10, 85, 54, 10, 85, 85, 56, 100, 85, /* 370 */ 58, 10, 100, 121, 60, 100, 85, 62, 85, 100, /* 380 */ 64, 66, 100, 259, 68, 100, 100, 32, 85, 100, /* 390 */ 161, 70, 85, 72, 162, 85, 100, 90, 100, 85, /* 400 */ 87, 254, 85, 75, 304, 85, 85, 84, 100, 85, /* 410 */ 94, 313, 100, 110, 96, 100, 85, 98, 85, 100, /* 420 */ 255, 137, 100, 141, 150, 256, 100, 179, 85, 100, /* 430 */ 225, 174, 85, 32, 154, 85, 152, 27, 28, 85, /* 440 */ 222, 229, 85, 76, 149, 73, 85, 131, 136, 85, /* 450 */ 133, 90, 19, 10, 24, 136, 216, 147, 151, 214, /* 460 */ 165, 169, 173, 216, 166, 170, 174, 114, 177, 305, /* 470 */ 175, 184, 10, 194, 202, 198, 209, 10, 198, 220, /* 480 */ 231, 314, 218, 174, 87, 236, 225, 253, 33, 174, /* 490 */ 36, 197, 204, 248, 208, 252, 73, 224, 77, 112, /* 500 */ 82, 250, 118, 233, 120, 126, 257, 129, 258, 132, /* 510 */ 264, 263, 261, 265, 31, 153, 286, 149, 146, 287, /* 520 */ 157, 216, 148, 288, 159, 289, 296, 163, 290, 291, /* 530 */ 167, 193, 292, 216, 293, 297, 195, 210, 215, 307, /* 540 */ 294, 176, 171, 188, 211, 339, 306, 221, 223, 226, /* 550 */ 316, 232, 315, 235, 192, 250, 250, 250, 205, 250, /* 560 */ 206, 250, 250, 250, 250, 250, 250, 250, 250, 250, /* 570 */ 250, 217, }; static YYCODETYPE yy_lookahead[] = { /* 0 */ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, /* 10 */ 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, /* 20 */ 21, 67, 68, 69, 25, 71, 27, 71, 1, 2, /* 30 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 40 */ 13, 14, 15, 16, 17, 18, 19, 49, 21, 2, /* 50 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 60 */ 13, 14, 15, 16, 17, 18, 19, 40, 21, 1, /* 70 */ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, /* 80 */ 12, 13, 14, 15, 16, 17, 18, 19, 24, 21, /* 90 */ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, /* 100 */ 18, 19, 14, 21, 40, 17, 74, 81, 20, 21, /* 110 */ 78, 79, 80, 25, 14, 18, 19, 17, 21, 0, /* 120 */ 20, 21, 96, 97, 25, 25, 24, 39, 40, 25, /* 130 */ 28, 29, 30, 31, 81, 33, 34, 49, 68, 39, /* 140 */ 70, 71, 54, 55, 56, 57, 58, 0, 49, 49, /* 150 */ 22, 98, 99, 49, 54, 55, 56, 57, 58, 14, /* 160 */ 68, 69, 17, 71, 36, 20, 21, 76, 14, 41, /* 170 */ 25, 43, 81, 17, 0, 84, 20, 21, 87, 25, /* 180 */ 68, 25, 81, 71, 39, 28, 29, 30, 31, 0, /* 190 */ 33, 34, 101, 0, 49, 39, 95, 96, 97, 54, /* 200 */ 55, 56, 57, 58, 68, 49, 70, 71, 23, 24, /* 210 */ 54, 55, 56, 57, 58, 0, 10, 11, 12, 13, /* 220 */ 14, 15, 16, 17, 18, 19, 52, 21, 11, 12, /* 230 */ 13, 14, 15, 16, 17, 18, 19, 21, 21, 78, /* 240 */ 79, 80, 60, 61, 62, 63, 64, 65, 66, 13, /* 250 */ 14, 15, 16, 17, 18, 19, 0, 21, 0, 44, /* 260 */ 45, 16, 17, 18, 19, 50, 21, 52, 76, 0, /* 270 */ 54, 89, 76, 81, 76, 49, 94, 81, 76, 81, /* 280 */ 76, 0, 0, 81, 85, 81, 72, 88, 84, 75, /* 290 */ 76, 87, 100, 101, 102, 81, 100, 101, 102, 101, /* 300 */ 102, 45, 100, 101, 102, 101, 50, 0, 52, 0, /* 310 */ 75, 76, 0, 76, 45, 101, 81, 46, 81, 0, /* 320 */ 51, 52, 76, 76, 87, 76, 45, 81, 81, 0, /* 330 */ 81, 24, 51, 52, 52, 49, 101, 76, 101, 93, /* 340 */ 76, 76, 81, 10, 76, 81, 81, 101, 101, 81, /* 350 */ 101, 76, 19, 76, 45, 81, 81, 45, 81, 0, /* 360 */ 53, 52, 101, 76, 52, 101, 101, 76, 81, 101, /* 370 */ 76, 52, 81, 99, 76, 81, 101, 76, 101, 81, /* 380 */ 76, 76, 81, 0, 76, 81, 81, 26, 101, 81, /* 390 */ 28, 76, 101, 76, 32, 101, 81, 24, 81, 101, /* 400 */ 39, 0, 101, 76, 0, 101, 101, 76, 81, 101, /* 410 */ 76, 0, 81, 40, 76, 81, 101, 76, 101, 81, /* 420 */ 0, 76, 81, 73, 76, 0, 81, 77, 101, 81, /* 430 */ 81, 81, 101, 26, 25, 101, 27, 47, 48, 101, /* 440 */ 91, 92, 101, 19, 35, 21, 101, 68, 44, 101, /* 450 */ 71, 24, 71, 52, 24, 44, 52, 82, 83, 67, /* 460 */ 28, 28, 77, 52, 32, 32, 81, 40, 25, 0, /* 470 */ 27, 26, 52, 38, 39, 24, 24, 52, 24, 77, /* 480 */ 67, 0, 90, 81, 39, 77, 81, 0, 25, 81, /* 490 */ 71, 40, 40, 0, 40, 0, 21, 92, 39, 39, /* 500 */ 54, 0, 46, 90, 24, 71, 0, 71, 0, 71, /* 510 */ 0, 0, 0, 0, 25, 25, 25, 35, 81, 25, /* 520 */ 28, 52, 83, 25, 28, 25, 0, 28, 25, 25, /* 530 */ 28, 81, 25, 52, 25, 0, 39, 88, 90, 0, /* 540 */ 25, 25, 28, 25, 25, 0, 0, 42, 24, 2, /* 550 */ 0, 90, 0, 23, 37, 103, 103, 103, 38, 103, /* 560 */ 39, 103, 103, 103, 103, 103, 103, 103, 103, 103, /* 570 */ 103, 49, }; #define YY_SHIFT_USE_DFLT (-3) static short yy_shift_ofst[] = { /* 0 */ 128, 19, 119, 147, 189, 193, 215, 256, 174, 258, /* 10 */ -2, 307, 226, 329, 286, 359, 269, 309, 282, 383, /* 20 */ 487, 271, 99, 430, 99, -3, 390, -3, -3, -3, /* 30 */ -3, 407, 463, -3, -3, 319, 493, 495, 156, 68, /* 40 */ 156, 156, 97, 156, 97, 156, 245, 156, 245, 156, /* 50 */ 245, 156, 206, 156, 206, 156, 236, 156, 236, 156, /* 60 */ 82, 156, 82, 156, 82, 156, 82, 156, 82, 156, /* 70 */ 82, 156, 217, 333, 156, 475, 459, 100, 68, 216, /* 80 */ -3, 446, -3, 156, 47, -3, 361, 88, 64, -3, /* 90 */ 100, -3, -3, 156, 424, 156, 475, 156, 27, -3, /* 100 */ -3, -3, -3, -3, -3, -3, -3, -3, -3, 373, /* 110 */ -3, 460, 100, 427, -3, 97, 501, 456, 104, 480, /* 120 */ 104, -3, -3, -3, -3, 401, 506, 281, 420, 508, /* 130 */ 312, 425, 510, 511, 512, 513, 156, 68, 145, 185, /* 140 */ 489, 102, 157, -3, -3, 489, 409, 482, -3, 156, /* 150 */ 68, -3, 490, -3, -3, 491, 492, 494, 496, 498, /* 160 */ 362, 500, 499, 503, 432, 504, 502, 507, 433, 509, /* 170 */ 514, 515, 489, -3, 443, 516, -3, -3, -3, -3, /* 180 */ 145, -3, -3, 445, 154, -3, -1, 518, -3, -3, /* 190 */ -3, 517, 489, 435, 497, 156, 451, 526, 156, -3, /* 200 */ 68, -3, 519, 452, 520, 521, 156, 454, 535, 519, /* 210 */ -3, -3, -3, 404, 469, 539, 522, 545, 546, 489, /* 220 */ 505, 489, 524, 489, -3, 547, 156, -3, 68, -3, /* 230 */ 411, 481, 550, 552, 530, 489, -3, }; #define YY_REDUCE_USE_DFLT (-47) static short yy_reduce_ofst[] = { /* 0 */ 182, -47, -47, -47, -47, -47, -46, 92, -44, -47, /* 10 */ -47, -47, -47, -47, -47, -47, 70, 112, 381, -47, /* 20 */ -47, -47, 101, -47, 26, -47, -47, -47, -47, -47, /* 30 */ -47, -47, -47, -47, -47, 419, -47, -47, 247, -47, /* 40 */ 249, 261, -47, 264, -47, 265, -47, 268, -47, 275, /* 50 */ -47, 277, -47, 287, -47, 291, -47, 294, -47, 298, /* 60 */ -47, 301, -47, 304, -47, 305, -47, 308, -47, 315, /* 70 */ -47, 317, -47, -47, 327, -47, -47, 192, -47, -47, /* 80 */ -47, -47, -47, 331, -47, -47, -47, 196, -47, -47, /* 90 */ 198, -47, -47, 334, -47, 338, -47, 341, -47, -47, /* 100 */ -47, -47, -47, -47, -47, -47, -47, -47, -47, -47, /* 110 */ -47, -47, 202, -47, -47, -47, -47, -47, 53, -47, /* 120 */ 274, -47, -47, -47, -47, 434, -47, 136, 436, -47, /* 130 */ 379, 438, -47, -47, -47, -47, 345, -47, 214, -47, /* 140 */ 350, 32, 161, -47, -47, 437, 375, 439, -47, 348, /* 150 */ -47, -47, -47, -47, -47, -47, -47, -47, -47, -47, /* 160 */ -47, -47, -47, -47, -47, -47, -47, -47, -47, -47, /* 170 */ -47, -47, 385, -47, -47, -47, -47, -47, -47, -47, /* 180 */ 235, -47, -47, -47, -47, -47, -47, -47, -47, -47, /* 190 */ -47, -47, 450, -47, -47, 91, -47, -47, 237, -47, /* 200 */ -47, -47, 199, -47, -47, -47, 204, -47, -47, 449, /* 210 */ -47, -47, -47, 392, 448, -47, -47, -47, -47, 402, /* 220 */ -47, 349, -47, 405, -47, -47, 246, -47, -47, -47, /* 230 */ 413, 461, -47, -47, -47, 408, -47, }; static YYACTIONTYPE yy_default[] = { /* 0 */ 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, /* 10 */ 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, /* 20 */ 382, 382, 382, 322, 382, 323, 325, 326, 327, 328, /* 30 */ 329, 381, 382, 380, 324, 382, 382, 382, 382, 335, /* 40 */ 382, 382, 340, 382, 342, 382, 343, 382, 344, 382, /* 50 */ 345, 382, 346, 382, 347, 382, 348, 382, 349, 382, /* 60 */ 350, 382, 351, 382, 352, 382, 353, 382, 354, 382, /* 70 */ 355, 382, 356, 382, 382, 357, 382, 382, 366, 382, /* 80 */ 367, 382, 368, 382, 370, 360, 381, 382, 382, 361, /* 90 */ 382, 363, 365, 382, 369, 382, 371, 382, 382, 372, /* 100 */ 373, 374, 375, 376, 377, 378, 379, 362, 364, 382, /* 110 */ 358, 382, 382, 382, 359, 341, 382, 382, 382, 330, /* 120 */ 382, 331, 333, 334, 332, 382, 382, 382, 382, 382, /* 130 */ 382, 382, 382, 382, 382, 382, 382, 321, 382, 382, /* 140 */ 382, 266, 267, 277, 279, 382, 280, 281, 283, 382, /* 150 */ 295, 282, 382, 284, 285, 382, 382, 382, 382, 382, /* 160 */ 382, 382, 382, 382, 382, 382, 382, 382, 382, 382, /* 170 */ 382, 382, 382, 275, 320, 382, 318, 319, 278, 276, /* 180 */ 382, 268, 270, 381, 382, 271, 274, 382, 272, 273, /* 190 */ 269, 382, 382, 382, 382, 382, 382, 382, 382, 298, /* 200 */ 300, 299, 382, 382, 382, 382, 382, 382, 382, 382, /* 210 */ 301, 303, 302, 382, 382, 382, 382, 382, 382, 382, /* 220 */ 382, 382, 308, 382, 309, 382, 382, 311, 312, 310, /* 230 */ 382, 382, 382, 382, 382, 382, 317, }; #define YY_SZ_ACTTAB (sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ int yyerrcnt; /* Shifts left before out of the error */ phql_ARG_SDECL /* A place to hold %extra_argument */ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ }; typedef struct yyParser yyParser; #ifndef NDEBUG #include <stdio.h> static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ void phql_Trace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *yyTokenName[] = { "$", "BETWEEN", "EQUALS", "NOTEQUALS", "LESS", "GREATER", "GREATEREQUAL", "LESSEQUAL", "AND", "OR", "LIKE", "BITWISE_AND", "BITWISE_OR", "DIVIDE", "TIMES", "MOD", "PLUS", "MINUS", "IS", "IN", "DISTINCT", "NOT", "SELECT", "FROM", "COMMA", "IDENTIFIER", "DOT", "AS", "JOIN", "INNER", "CROSS", "LEFT", "OUTER", "RIGHT", "FULL", "ON", "INSERT", "INTO", "VALUES", "BRACKET_OPEN", "BRACKET_CLOSE", "UPDATE", "SET", "DELETE", "WHERE", "ORDER", "BY", "ASC", "DESC", "INTEGER", "GROUP", "HAVING", "LIMIT", "OFFSET", "NULL", "STRING", "DOUBLE", "NPLACEHOLDER", "SPLACEHOLDER", "error", "program", "query_language", "select_statement", "insert_statement", "update_statement", "delete_statement", "select_clause", "where_clause", "order_clause", "group_clause", "having_clause", "select_limit_clause", "column_list", "associated_name_list", "join_list", "column_item", "expr", "associated_name", "join_item", "join_clause", "join_type", "qualified_name", "join_associated_name", "join_conditions", "values_list", "field_list", "value_list", "value_item", "field_item", "update_clause", "limit_clause", "update_item_list", "update_item", "new_value", "delete_clause", "order_list", "order_item", "order_qualified_or_int", "group_list", "group_item", "argument_list", "function_call", "argument_item", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *yyRuleName[] = { /* 0 */ "program ::= query_language", /* 1 */ "query_language ::= select_statement", /* 2 */ "query_language ::= insert_statement", /* 3 */ "query_language ::= update_statement", /* 4 */ "query_language ::= delete_statement", /* 5 */ "select_statement ::= select_clause", /* 6 */ "select_statement ::= select_clause where_clause", /* 7 */ "select_statement ::= select_clause where_clause order_clause", /* 8 */ "select_statement ::= select_clause where_clause group_clause", /* 9 */ "select_statement ::= select_clause where_clause group_clause having_clause", /* 10 */ "select_statement ::= select_clause where_clause group_clause order_clause", /* 11 */ "select_statement ::= select_clause where_clause group_clause order_clause select_limit_clause", /* 12 */ "select_statement ::= select_clause where_clause group_clause having_clause order_clause", /* 13 */ "select_statement ::= select_clause where_clause select_limit_clause", /* 14 */ "select_statement ::= select_clause where_clause order_clause select_limit_clause", /* 15 */ "select_statement ::= select_clause where_clause group_clause select_limit_clause", /* 16 */ "select_statement ::= select_clause where_clause group_clause having_clause select_limit_clause", /* 17 */ "select_statement ::= select_clause order_clause", /* 18 */ "select_statement ::= select_clause group_clause order_clause", /* 19 */ "select_statement ::= select_clause group_clause having_clause order_clause", /* 20 */ "select_statement ::= select_clause order_clause select_limit_clause", /* 21 */ "select_statement ::= select_clause group_clause order_clause select_limit_clause", /* 22 */ "select_statement ::= select_clause where_clause group_clause having_clause order_clause select_limit_clause", /* 23 */ "select_statement ::= select_clause group_clause", /* 24 */ "select_statement ::= select_clause group_clause select_limit_clause", /* 25 */ "select_statement ::= select_clause group_clause having_clause", /* 26 */ "select_statement ::= select_clause group_clause having_clause select_limit_clause", /* 27 */ "select_statement ::= select_clause group_clause having_clause order_clause select_limit_clause", /* 28 */ "select_statement ::= select_clause select_limit_clause", /* 29 */ "select_clause ::= SELECT column_list FROM associated_name_list", /* 30 */ "select_clause ::= SELECT column_list FROM associated_name_list join_list", /* 31 */ "column_list ::= column_list COMMA column_item", /* 32 */ "column_list ::= column_item", /* 33 */ "column_item ::= TIMES", /* 34 */ "column_item ::= IDENTIFIER DOT TIMES", /* 35 */ "column_item ::= expr AS IDENTIFIER", /* 36 */ "column_item ::= expr IDENTIFIER", /* 37 */ "column_item ::= expr", /* 38 */ "associated_name_list ::= associated_name_list COMMA associated_name", /* 39 */ "associated_name_list ::= associated_name", /* 40 */ "join_list ::= join_list join_item", /* 41 */ "join_list ::= join_item", /* 42 */ "join_item ::= join_clause", /* 43 */ "join_clause ::= join_type qualified_name", /* 44 */ "join_clause ::= join_type qualified_name join_associated_name", /* 45 */ "join_clause ::= join_type qualified_name join_conditions", /* 46 */ "join_clause ::= join_type qualified_name join_associated_name join_conditions", /* 47 */ "join_associated_name ::= AS IDENTIFIER", /* 48 */ "join_associated_name ::= IDENTIFIER", /* 49 */ "join_type ::= JOIN", /* 50 */ "join_type ::= INNER JOIN", /* 51 */ "join_type ::= CROSS JOIN", /* 52 */ "join_type ::= LEFT JOIN", /* 53 */ "join_type ::= LEFT OUTER JOIN", /* 54 */ "join_type ::= RIGHT JOIN", /* 55 */ "join_type ::= RIGHT OUTER JOIN", /* 56 */ "join_type ::= FULL JOIN", /* 57 */ "join_type ::= FULL OUTER JOIN", /* 58 */ "join_conditions ::= ON expr", /* 59 */ "insert_statement ::= INSERT INTO qualified_name VALUES BRACKET_OPEN values_list BRACKET_CLOSE", /* 60 */ "insert_statement ::= INSERT INTO qualified_name BRACKET_OPEN field_list BRACKET_CLOSE VALUES BRACKET_OPEN values_list BRACKET_CLOSE", /* 61 */ "values_list ::= values_list COMMA value_item", /* 62 */ "values_list ::= value_item", /* 63 */ "value_item ::= expr", /* 64 */ "field_list ::= field_list COMMA field_item", /* 65 */ "field_list ::= field_item", /* 66 */ "field_item ::= IDENTIFIER", /* 67 */ "update_statement ::= update_clause", /* 68 */ "update_statement ::= update_clause where_clause", /* 69 */ "update_statement ::= update_clause limit_clause", /* 70 */ "update_statement ::= update_clause where_clause limit_clause", /* 71 */ "update_clause ::= UPDATE associated_name SET update_item_list", /* 72 */ "update_item_list ::= update_item_list COMMA update_item", /* 73 */ "update_item_list ::= update_item", /* 74 */ "update_item ::= qualified_name EQUALS new_value", /* 75 */ "new_value ::= expr", /* 76 */ "delete_statement ::= delete_clause", /* 77 */ "delete_statement ::= delete_clause where_clause", /* 78 */ "delete_statement ::= delete_clause limit_clause", /* 79 */ "delete_statement ::= delete_clause where_clause limit_clause", /* 80 */ "delete_clause ::= DELETE FROM associated_name", /* 81 */ "associated_name ::= qualified_name AS IDENTIFIER", /* 82 */ "associated_name ::= qualified_name IDENTIFIER", /* 83 */ "associated_name ::= qualified_name", /* 84 */ "where_clause ::= WHERE expr", /* 85 */ "order_clause ::= ORDER BY order_list", /* 86 */ "order_list ::= order_list COMMA order_item", /* 87 */ "order_list ::= order_item", /* 88 */ "order_item ::= order_qualified_or_int", /* 89 */ "order_item ::= order_qualified_or_int ASC", /* 90 */ "order_item ::= order_qualified_or_int DESC", /* 91 */ "order_qualified_or_int ::= qualified_name", /* 92 */ "order_qualified_or_int ::= INTEGER", /* 93 */ "group_clause ::= GROUP BY group_list", /* 94 */ "group_list ::= group_list COMMA group_item", /* 95 */ "group_list ::= group_item", /* 96 */ "group_item ::= qualified_name", /* 97 */ "group_item ::= INTEGER", /* 98 */ "having_clause ::= HAVING expr", /* 99 */ "select_limit_clause ::= LIMIT INTEGER", /* 100 */ "select_limit_clause ::= LIMIT INTEGER COMMA INTEGER", /* 101 */ "select_limit_clause ::= LIMIT INTEGER OFFSET INTEGER", /* 102 */ "limit_clause ::= LIMIT INTEGER", /* 103 */ "expr ::= MINUS expr", /* 104 */ "expr ::= expr MINUS expr", /* 105 */ "expr ::= expr PLUS expr", /* 106 */ "expr ::= expr TIMES expr", /* 107 */ "expr ::= expr DIVIDE expr", /* 108 */ "expr ::= expr MOD expr", /* 109 */ "expr ::= expr AND expr", /* 110 */ "expr ::= expr OR expr", /* 111 */ "expr ::= expr BITWISE_AND expr", /* 112 */ "expr ::= expr BITWISE_OR expr", /* 113 */ "expr ::= expr EQUALS expr", /* 114 */ "expr ::= expr NOTEQUALS expr", /* 115 */ "expr ::= expr LESS expr", /* 116 */ "expr ::= expr GREATER expr", /* 117 */ "expr ::= expr GREATEREQUAL expr", /* 118 */ "expr ::= expr LESSEQUAL expr", /* 119 */ "expr ::= expr LIKE expr", /* 120 */ "expr ::= expr NOT LIKE expr", /* 121 */ "expr ::= expr IN BRACKET_OPEN argument_list BRACKET_CLOSE", /* 122 */ "expr ::= expr NOT IN BRACKET_OPEN argument_list BRACKET_CLOSE", /* 123 */ "expr ::= function_call", /* 124 */ "function_call ::= IDENTIFIER BRACKET_OPEN argument_list BRACKET_CLOSE", /* 125 */ "function_call ::= IDENTIFIER BRACKET_OPEN BRACKET_CLOSE", /* 126 */ "argument_list ::= argument_list COMMA argument_item", /* 127 */ "argument_list ::= argument_item", /* 128 */ "argument_item ::= TIMES", /* 129 */ "argument_item ::= expr", /* 130 */ "expr ::= expr IS NULL", /* 131 */ "expr ::= expr IS NOT NULL", /* 132 */ "expr ::= DISTINCT expr", /* 133 */ "expr ::= expr BETWEEN expr", /* 134 */ "expr ::= NOT expr", /* 135 */ "expr ::= BRACKET_OPEN expr BRACKET_CLOSE", /* 136 */ "expr ::= qualified_name", /* 137 */ "expr ::= INTEGER", /* 138 */ "expr ::= STRING", /* 139 */ "expr ::= DOUBLE", /* 140 */ "expr ::= NULL", /* 141 */ "expr ::= NPLACEHOLDER", /* 142 */ "expr ::= SPLACEHOLDER", /* 143 */ "qualified_name ::= IDENTIFIER DOT IDENTIFIER", /* 144 */ "qualified_name ::= IDENTIFIER", }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *phql_TokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to phql_ and phql_Free. */ void *phql_Alloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: // 486 "parser.lemon" { if ((yypminor->yy0)) { if ((yypminor->yy0)->free_flag) { efree((yypminor->yy0)->token); } efree((yypminor->yy0)); } } // 1094 "parser.c" break; case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 85: case 86: case 88: case 89: case 90: case 91: case 92: case 94: case 95: case 96: case 98: case 99: case 100: case 101: case 102: // 499 "parser.lemon" { zval_ptr_dtor(&(yypminor->yy10)); } // 1136 "parser.c" break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor( yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: ** <ul> ** <li> A pointer to the parser. This should be a pointer ** obtained from phql_Alloc. ** <li> A pointer to a function used to reclaim memory obtained ** from malloc. ** </ul> */ void phql_Free( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; /* if( pParser->yyidx<0 ) return YY_NO_ACTION; */ i = yy_shift_ofst[stateno]; if( i==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) && (iFallback = yyFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; i = yy_reduce_ofst[stateno]; if( i==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; if( yypParser->yyidx>=YYSTACKDEPTH ){ phql_ARG_FETCH; yypParser->yyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ phql_ARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = yyNewState; yytos->major = yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 60, 1 }, { 61, 1 }, { 61, 1 }, { 61, 1 }, { 61, 1 }, { 62, 1 }, { 62, 2 }, { 62, 3 }, { 62, 3 }, { 62, 4 }, { 62, 4 }, { 62, 5 }, { 62, 5 }, { 62, 3 }, { 62, 4 }, { 62, 4 }, { 62, 5 }, { 62, 2 }, { 62, 3 }, { 62, 4 }, { 62, 3 }, { 62, 4 }, { 62, 6 }, { 62, 2 }, { 62, 3 }, { 62, 3 }, { 62, 4 }, { 62, 5 }, { 62, 2 }, { 66, 4 }, { 66, 5 }, { 72, 3 }, { 72, 1 }, { 75, 1 }, { 75, 3 }, { 75, 3 }, { 75, 2 }, { 75, 1 }, { 73, 3 }, { 73, 1 }, { 74, 2 }, { 74, 1 }, { 78, 1 }, { 79, 2 }, { 79, 3 }, { 79, 3 }, { 79, 4 }, { 82, 2 }, { 82, 1 }, { 80, 1 }, { 80, 2 }, { 80, 2 }, { 80, 2 }, { 80, 3 }, { 80, 2 }, { 80, 3 }, { 80, 2 }, { 80, 3 }, { 83, 2 }, { 63, 7 }, { 63, 10 }, { 84, 3 }, { 84, 1 }, { 87, 1 }, { 85, 3 }, { 85, 1 }, { 88, 1 }, { 64, 1 }, { 64, 2 }, { 64, 2 }, { 64, 3 }, { 89, 4 }, { 91, 3 }, { 91, 1 }, { 92, 3 }, { 93, 1 }, { 65, 1 }, { 65, 2 }, { 65, 2 }, { 65, 3 }, { 94, 3 }, { 77, 3 }, { 77, 2 }, { 77, 1 }, { 67, 2 }, { 68, 3 }, { 95, 3 }, { 95, 1 }, { 96, 1 }, { 96, 2 }, { 96, 2 }, { 97, 1 }, { 97, 1 }, { 69, 3 }, { 98, 3 }, { 98, 1 }, { 99, 1 }, { 99, 1 }, { 70, 2 }, { 71, 2 }, { 71, 4 }, { 71, 4 }, { 90, 2 }, { 76, 2 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 3 }, { 76, 4 }, { 76, 5 }, { 76, 6 }, { 76, 1 }, { 101, 4 }, { 101, 3 }, { 100, 3 }, { 100, 1 }, { 102, 1 }, { 102, 1 }, { 76, 3 }, { 76, 4 }, { 76, 2 }, { 76, 3 }, { 76, 2 }, { 76, 3 }, { 76, 1 }, { 76, 1 }, { 76, 1 }, { 76, 1 }, { 76, 1 }, { 76, 1 }, { 76, 1 }, { 81, 3 }, { 81, 1 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ phql_ARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno<sizeof(yyRuleName)/sizeof(yyRuleName[0]) ){ fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, yyRuleName[yyruleno]); } #endif /* NDEBUG */ switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** // <lineno> <grammarfile> ** { ... } // User supplied code ** // <lineno> <thisfile> ** break; */ case 0: // 495 "parser.lemon" { status->ret = yymsp[0].minor.yy10; } // 1498 "parser.c" break; case 1: case 2: case 3: case 4: case 32: case 39: case 41: case 42: case 62: case 63: case 65: case 73: case 75: case 87: case 91: case 95: case 96: case 123: case 129: case 136: // 501 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; } // 1524 "parser.c" break; case 5: // 519 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[0].minor.yy10, NULL, NULL, NULL, NULL, NULL); } // 1531 "parser.c" break; case 6: // 523 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL, NULL, NULL, NULL); } // 1538 "parser.c" break; case 7: // 527 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL, NULL, NULL); } // 1545 "parser.c" break; case 8: // 531 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10, NULL, NULL); } // 1552 "parser.c" break; case 9: // 535 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, NULL, yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL); } // 1559 "parser.c" break; case 10: // 539 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, yymsp[0].minor.yy10, yymsp[-1].minor.yy10, NULL, NULL); } // 1566 "parser.c" break; case 11: // 543 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-4].minor.yy10, yymsp[-3].minor.yy10, yymsp[-1].minor.yy10, yymsp[-2].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1573 "parser.c" break; case 12: // 547 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-4].minor.yy10, yymsp[-3].minor.yy10, yymsp[0].minor.yy10, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL); } // 1580 "parser.c" break; case 13: // 551 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL, NULL, NULL, yymsp[0].minor.yy10); } // 1587 "parser.c" break; case 14: // 555 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL, NULL, yymsp[0].minor.yy10); } // 1594 "parser.c" break; case 15: // 559 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, NULL, yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1601 "parser.c" break; case 16: // 563 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-4].minor.yy10, yymsp[-3].minor.yy10, NULL, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 1608 "parser.c" break; case 17: // 567 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10, NULL, NULL, NULL); } // 1615 "parser.c" break; case 18: // 571 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, NULL, yymsp[0].minor.yy10, yymsp[-1].minor.yy10, NULL, NULL); } // 1622 "parser.c" break; case 19: // 575 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, NULL, yymsp[0].minor.yy10, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL); } // 1629 "parser.c" break; case 20: // 579 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, NULL, yymsp[-1].minor.yy10, NULL, NULL, yymsp[0].minor.yy10); } // 1636 "parser.c" break; case 21: // 583 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, NULL, yymsp[-1].minor.yy10, yymsp[-2].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1643 "parser.c" break; case 22: // 587 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-5].minor.yy10, yymsp[-4].minor.yy10, yymsp[-1].minor.yy10, yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); } // 1650 "parser.c" break; case 23: // 591 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-1].minor.yy10, NULL, NULL, yymsp[0].minor.yy10, NULL, NULL); } // 1657 "parser.c" break; case 24: // 595 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, NULL, NULL, yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1664 "parser.c" break; case 25: // 599 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-2].minor.yy10, NULL, NULL, yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL); } // 1671 "parser.c" break; case 26: // 603 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-3].minor.yy10, NULL, NULL, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 1678 "parser.c" break; case 27: // 607 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-4].minor.yy10, NULL, yymsp[-1].minor.yy10, yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); } // 1685 "parser.c" break; case 28: // 611 "parser.lemon" { yygotominor.yy10 = phql_ret_select_statement(yymsp[-1].minor.yy10, NULL, NULL, NULL, NULL, yymsp[0].minor.yy10); } // 1692 "parser.c" break; case 29: // 617 "parser.lemon" { yygotominor.yy10 = phql_ret_select_clause(yymsp[-2].minor.yy10, yymsp[0].minor.yy10, NULL); yy_destructor(22,&yymsp[-3].minor); yy_destructor(23,&yymsp[-1].minor); } // 1701 "parser.c" break; case 30: // 621 "parser.lemon" { yygotominor.yy10 = phql_ret_select_clause(yymsp[-3].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); yy_destructor(22,&yymsp[-4].minor); yy_destructor(23,&yymsp[-2].minor); } // 1710 "parser.c" break; case 31: case 38: case 61: case 64: case 72: case 86: case 94: case 126: // 627 "parser.lemon" { yygotominor.yy10 = phql_ret_zval_list(yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(24,&yymsp[-1].minor); } // 1725 "parser.c" break; case 33: case 128: // 637 "parser.lemon" { yygotominor.yy10 = phql_ret_column_item(PHQL_T_ALL, NULL, NULL, NULL); yy_destructor(14,&yymsp[0].minor); } // 1734 "parser.c" break; case 34: // 641 "parser.lemon" { yygotominor.yy10 = phql_ret_column_item(PHQL_T_DOMAINALL, NULL, yymsp[-2].minor.yy0, NULL); yy_destructor(26,&yymsp[-1].minor); yy_destructor(14,&yymsp[0].minor); } // 1743 "parser.c" break; case 35: // 645 "parser.lemon" { yygotominor.yy10 = phql_ret_column_item(PHQL_T_EXPR, yymsp[-2].minor.yy10, NULL, yymsp[0].minor.yy0); yy_destructor(27,&yymsp[-1].minor); } // 1751 "parser.c" break; case 36: // 649 "parser.lemon" { yygotominor.yy10 = phql_ret_column_item(PHQL_T_EXPR, yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy0); } // 1758 "parser.c" break; case 37: // 653 "parser.lemon" { yygotominor.yy10 = phql_ret_column_item(PHQL_T_EXPR, yymsp[0].minor.yy10, NULL, NULL); } // 1765 "parser.c" break; case 40: // 669 "parser.lemon" { yygotominor.yy10 = phql_ret_zval_list(yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 1772 "parser.c" break; case 43: // 686 "parser.lemon" { yygotominor.yy10 = phql_ret_join_item(yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL, NULL); } // 1779 "parser.c" break; case 44: // 691 "parser.lemon" { yygotominor.yy10 = phql_ret_join_item(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL); } // 1786 "parser.c" break; case 45: // 696 "parser.lemon" { yygotominor.yy10 = phql_ret_join_item(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1793 "parser.c" break; case 46: // 701 "parser.lemon" { yygotominor.yy10 = phql_ret_join_item(yymsp[-3].minor.yy10, yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 1800 "parser.c" break; case 47: // 707 "parser.lemon" { yygotominor.yy10 = phql_ret_qualified_name(yymsp[0].minor.yy0, NULL); yy_destructor(27,&yymsp[-1].minor); } // 1808 "parser.c" break; case 48: case 66: case 144: // 711 "parser.lemon" { yygotominor.yy10 = phql_ret_qualified_name(yymsp[0].minor.yy0, NULL); } // 1817 "parser.c" break; case 49: // 717 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_INNERJOIN); yy_destructor(28,&yymsp[0].minor); } // 1825 "parser.c" break; case 50: // 721 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_INNERJOIN); yy_destructor(29,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1834 "parser.c" break; case 51: // 725 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_CROSSJOIN); yy_destructor(30,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1843 "parser.c" break; case 52: // 729 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_LEFTJOIN); yy_destructor(31,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1852 "parser.c" break; case 53: // 733 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_LEFTJOIN); yy_destructor(31,&yymsp[-2].minor); yy_destructor(32,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1862 "parser.c" break; case 54: // 737 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_RIGHTJOIN); yy_destructor(33,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1871 "parser.c" break; case 55: // 741 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_RIGHTJOIN); yy_destructor(33,&yymsp[-2].minor); yy_destructor(32,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1881 "parser.c" break; case 56: // 745 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_FULLJOIN); yy_destructor(34,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1890 "parser.c" break; case 57: // 749 "parser.lemon" { yygotominor.yy10 = phql_ret_join_type(PHQL_T_FULLJOIN); yy_destructor(34,&yymsp[-2].minor); yy_destructor(32,&yymsp[-1].minor); yy_destructor(28,&yymsp[0].minor); } // 1900 "parser.c" break; case 58: // 755 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; yy_destructor(35,&yymsp[-1].minor); } // 1908 "parser.c" break; case 59: // 762 "parser.lemon" { yygotominor.yy10 = phql_ret_insert_statement(yymsp[-4].minor.yy10, NULL, yymsp[-1].minor.yy10); yy_destructor(36,&yymsp[-6].minor); yy_destructor(37,&yymsp[-5].minor); yy_destructor(38,&yymsp[-3].minor); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 1920 "parser.c" break; case 60: // 766 "parser.lemon" { yygotominor.yy10 = phql_ret_insert_statement(yymsp[-7].minor.yy10, yymsp[-5].minor.yy10, yymsp[-1].minor.yy10); yy_destructor(36,&yymsp[-9].minor); yy_destructor(37,&yymsp[-8].minor); yy_destructor(39,&yymsp[-6].minor); yy_destructor(40,&yymsp[-4].minor); yy_destructor(38,&yymsp[-3].minor); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 1934 "parser.c" break; case 67: // 804 "parser.lemon" { yygotominor.yy10 = phql_ret_update_statement(yymsp[0].minor.yy10, NULL, NULL); } // 1941 "parser.c" break; case 68: // 808 "parser.lemon" { yygotominor.yy10 = phql_ret_update_statement(yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL); } // 1948 "parser.c" break; case 69: // 812 "parser.lemon" { yygotominor.yy10 = phql_ret_update_statement(yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10); } // 1955 "parser.c" break; case 70: // 816 "parser.lemon" { yygotominor.yy10 = phql_ret_update_statement(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 1962 "parser.c" break; case 71: // 822 "parser.lemon" { yygotominor.yy10 = phql_ret_update_clause(yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(41,&yymsp[-3].minor); yy_destructor(42,&yymsp[-1].minor); } // 1971 "parser.c" break; case 74: // 838 "parser.lemon" { yygotominor.yy10 = phql_ret_update_item(yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(2,&yymsp[-1].minor); } // 1979 "parser.c" break; case 76: // 850 "parser.lemon" { yygotominor.yy10 = phql_ret_delete_statement(yymsp[0].minor.yy10, NULL, NULL); } // 1986 "parser.c" break; case 77: // 854 "parser.lemon" { yygotominor.yy10 = phql_ret_delete_statement(yymsp[-1].minor.yy10, yymsp[0].minor.yy10, NULL); } // 1993 "parser.c" break; case 78: // 858 "parser.lemon" { yygotominor.yy10 = phql_ret_delete_statement(yymsp[-1].minor.yy10, NULL, yymsp[0].minor.yy10); } // 2000 "parser.c" break; case 79: // 862 "parser.lemon" { yygotominor.yy10 = phql_ret_delete_statement(yymsp[-2].minor.yy10, yymsp[-1].minor.yy10, yymsp[0].minor.yy10); } // 2007 "parser.c" break; case 80: // 868 "parser.lemon" { yygotominor.yy10 = phql_ret_delete_clause(yymsp[0].minor.yy10); yy_destructor(43,&yymsp[-2].minor); yy_destructor(23,&yymsp[-1].minor); } // 2016 "parser.c" break; case 81: // 874 "parser.lemon" { yygotominor.yy10 = phql_ret_assoc_name(yymsp[-2].minor.yy10, yymsp[0].minor.yy0); yy_destructor(27,&yymsp[-1].minor); } // 2024 "parser.c" break; case 82: // 878 "parser.lemon" { yygotominor.yy10 = phql_ret_assoc_name(yymsp[-1].minor.yy10, yymsp[0].minor.yy0); } // 2031 "parser.c" break; case 83: // 882 "parser.lemon" { yygotominor.yy10 = phql_ret_assoc_name(yymsp[0].minor.yy10, NULL); } // 2038 "parser.c" break; case 84: // 888 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; yy_destructor(44,&yymsp[-1].minor); } // 2046 "parser.c" break; case 85: // 894 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; yy_destructor(45,&yymsp[-2].minor); yy_destructor(46,&yymsp[-1].minor); } // 2055 "parser.c" break; case 88: // 910 "parser.lemon" { yygotominor.yy10 = phql_ret_order_item(yymsp[0].minor.yy10, 0); } // 2062 "parser.c" break; case 89: // 914 "parser.lemon" { yygotominor.yy10 = phql_ret_order_item(yymsp[-1].minor.yy10, PHQL_T_ASC); yy_destructor(47,&yymsp[0].minor); } // 2070 "parser.c" break; case 90: // 918 "parser.lemon" { yygotominor.yy10 = phql_ret_order_item(yymsp[-1].minor.yy10, PHQL_T_DESC); yy_destructor(48,&yymsp[0].minor); } // 2078 "parser.c" break; case 92: case 97: case 137: // 926 "parser.lemon" { yygotominor.yy10 = phql_ret_literal_zval(PHQL_T_INTEGER, yymsp[0].minor.yy0); } // 2087 "parser.c" break; case 93: // 932 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; yy_destructor(50,&yymsp[-2].minor); yy_destructor(46,&yymsp[-1].minor); } // 2096 "parser.c" break; case 98: // 958 "parser.lemon" { yygotominor.yy10 = yymsp[0].minor.yy10; yy_destructor(51,&yymsp[-1].minor); } // 2104 "parser.c" break; case 99: case 102: // 964 "parser.lemon" { yygotominor.yy10 = phql_ret_limit_clause(yymsp[0].minor.yy0, NULL); yy_destructor(52,&yymsp[-1].minor); } // 2113 "parser.c" break; case 100: // 968 "parser.lemon" { yygotominor.yy10 = phql_ret_limit_clause(yymsp[0].minor.yy0, yymsp[-2].minor.yy0); yy_destructor(52,&yymsp[-3].minor); yy_destructor(24,&yymsp[-1].minor); } // 2122 "parser.c" break; case 101: // 972 "parser.lemon" { yygotominor.yy10 = phql_ret_limit_clause(yymsp[-2].minor.yy0, yymsp[0].minor.yy0); yy_destructor(52,&yymsp[-3].minor); yy_destructor(53,&yymsp[-1].minor); } // 2131 "parser.c" break; case 103: // 984 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_MINUS, NULL, yymsp[0].minor.yy10); yy_destructor(17,&yymsp[-1].minor); } // 2139 "parser.c" break; case 104: // 988 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_SUB, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(17,&yymsp[-1].minor); } // 2147 "parser.c" break; case 105: // 992 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_ADD, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(16,&yymsp[-1].minor); } // 2155 "parser.c" break; case 106: // 996 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_MUL, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(14,&yymsp[-1].minor); } // 2163 "parser.c" break; case 107: // 1000 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_DIV, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(13,&yymsp[-1].minor); } // 2171 "parser.c" break; case 108: // 1004 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_MOD, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(15,&yymsp[-1].minor); } // 2179 "parser.c" break; case 109: // 1008 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_AND, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(8,&yymsp[-1].minor); } // 2187 "parser.c" break; case 110: // 1012 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_OR, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(9,&yymsp[-1].minor); } // 2195 "parser.c" break; case 111: // 1016 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_BITWISE_AND, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(11,&yymsp[-1].minor); } // 2203 "parser.c" break; case 112: // 1020 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_BITWISE_OR, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(12,&yymsp[-1].minor); } // 2211 "parser.c" break; case 113: // 1024 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_EQUALS, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(2,&yymsp[-1].minor); } // 2219 "parser.c" break; case 114: // 1028 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_NOTEQUALS, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(3,&yymsp[-1].minor); } // 2227 "parser.c" break; case 115: // 1032 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_LESS, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(4,&yymsp[-1].minor); } // 2235 "parser.c" break; case 116: // 1036 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_GREATER, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(5,&yymsp[-1].minor); } // 2243 "parser.c" break; case 117: // 1040 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_GREATEREQUAL, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(6,&yymsp[-1].minor); } // 2251 "parser.c" break; case 118: // 1044 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_LESSEQUAL, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(7,&yymsp[-1].minor); } // 2259 "parser.c" break; case 119: // 1048 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_LIKE, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(10,&yymsp[-1].minor); } // 2267 "parser.c" break; case 120: // 1052 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_NLIKE, yymsp[-3].minor.yy10, yymsp[0].minor.yy10); yy_destructor(21,&yymsp[-2].minor); yy_destructor(10,&yymsp[-1].minor); } // 2276 "parser.c" break; case 121: // 1056 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_IN, yymsp[-4].minor.yy10, yymsp[-1].minor.yy10); yy_destructor(19,&yymsp[-3].minor); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 2286 "parser.c" break; case 122: // 1060 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_NOTIN, yymsp[-5].minor.yy10, yymsp[-1].minor.yy10); yy_destructor(21,&yymsp[-4].minor); yy_destructor(19,&yymsp[-3].minor); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 2297 "parser.c" break; case 124: // 1070 "parser.lemon" { yygotominor.yy10 = phql_ret_func_call(yymsp[-3].minor.yy0, yymsp[-1].minor.yy10); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 2306 "parser.c" break; case 125: // 1074 "parser.lemon" { yygotominor.yy10 = phql_ret_func_call(yymsp[-2].minor.yy0, NULL); yy_destructor(39,&yymsp[-1].minor); yy_destructor(40,&yymsp[0].minor); } // 2315 "parser.c" break; case 127: // 1084 "parser.lemon" { yygotominor.yy10 = phql_ret_zval_list(yymsp[0].minor.yy10, NULL); } // 2322 "parser.c" break; case 130: // 1098 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_ISNULL, yymsp[-2].minor.yy10, NULL); yy_destructor(18,&yymsp[-1].minor); yy_destructor(54,&yymsp[0].minor); } // 2331 "parser.c" break; case 131: // 1102 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_ISNOTNULL, yymsp[-3].minor.yy10, NULL); yy_destructor(18,&yymsp[-2].minor); yy_destructor(21,&yymsp[-1].minor); yy_destructor(54,&yymsp[0].minor); } // 2341 "parser.c" break; case 132: // 1106 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_DISTINCT, NULL, yymsp[0].minor.yy10); yy_destructor(20,&yymsp[-1].minor); } // 2349 "parser.c" break; case 133: // 1110 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_BETWEEN, yymsp[-2].minor.yy10, yymsp[0].minor.yy10); yy_destructor(1,&yymsp[-1].minor); } // 2357 "parser.c" break; case 134: // 1114 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_NOT, NULL, yymsp[0].minor.yy10); yy_destructor(21,&yymsp[-1].minor); } // 2365 "parser.c" break; case 135: // 1118 "parser.lemon" { yygotominor.yy10 = phql_ret_expr(PHQL_T_ENCLOSED, yymsp[-1].minor.yy10, NULL); yy_destructor(39,&yymsp[-2].minor); yy_destructor(40,&yymsp[0].minor); } // 2374 "parser.c" break; case 138: // 1130 "parser.lemon" { yygotominor.yy10 = phql_ret_literal_zval(PHQL_T_STRING, yymsp[0].minor.yy0); } // 2381 "parser.c" break; case 139: // 1134 "parser.lemon" { yygotominor.yy10 = phql_ret_literal_zval(PHQL_T_DOUBLE, yymsp[0].minor.yy0); } // 2388 "parser.c" break; case 140: // 1138 "parser.lemon" { yygotominor.yy10 = phql_ret_literal_zval(PHQL_T_NULL, NULL); yy_destructor(54,&yymsp[0].minor); } // 2396 "parser.c" break; case 141: // 1142 "parser.lemon" { yygotominor.yy10 = phql_ret_placeholder_zval(PHQL_T_NPLACEHOLDER, yymsp[0].minor.yy0); } // 2403 "parser.c" break; case 142: // 1146 "parser.lemon" { yygotominor.yy10 = phql_ret_placeholder_zval(PHQL_T_SPLACEHOLDER, yymsp[0].minor.yy0); } // 2410 "parser.c" break; case 143: // 1152 "parser.lemon" { yygotominor.yy10 = phql_ret_qualified_name(yymsp[-2].minor.yy0, yymsp[0].minor.yy0); yy_destructor(26,&yymsp[-1].minor); } // 2418 "parser.c" break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yypParser,yygoto); if( yyact < YYNSTATE ){ yy_shift(yypParser,yyact,yygoto,&yygotominor); }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ phql_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ phql_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ phql_ARG_FETCH; #define TOKEN (yyminor.yy0) // 419 "parser.lemon" if (status->scanner_state->start_length) { { char *token_name = NULL; int token_found = 0; unsigned int token_length; const phql_token_names *tokens = phql_tokens; int active_token = status->scanner_state->active_token; int near_length = status->scanner_state->start_length; if (active_token) { do { if (tokens->code == active_token) { token_name = tokens->name; token_length = tokens->length; token_found = 1; break; } ++tokens; } while (tokens[0].code != 0); } if (!token_name) { token_length = strlen("UNKNOWN"); token_name = estrndup("UNKNOWN", token_length); token_found = 0; } status->syntax_error_len = 64 + status->token->len + token_length + near_length; status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); if (near_length > 0) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), near to '%s'", token_name, status->token->value, status->scanner_state->start); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, near to '%s'", token_name, status->scanner_state->start); } } else { if (active_token != PHQL_T_IGNORE) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), at the end of query", token_name, status->token->value); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, at the end of query", token_name); } } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected EOF, at the end of query"); } status->syntax_error[status->syntax_error_len-1] = '\0'; } if (!token_found) { if (token_name) { efree(token_name); } } } } else { status->syntax_error_len = strlen("Syntax error, unexpected EOF"); status->syntax_error = estrndup("Syntax error, unexpected EOF", status->syntax_error_len); } status->status = PHQL_PARSING_FAILED; // 2527 "parser.c" phql_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ phql_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ phql_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "phql_Alloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ void phql_( void *yyp, /* The parser */ int yymajor, /* The major token code number */ phql_TOKENTYPE yyminor /* The value for the token */ phql_ARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ int yyerrorhit = 0; /* True if yymajor has invoked an error */ yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ if( yymajor==0 ) return; yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); phql_ARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyact<YYNSTATE ){ yy_shift(yypParser,yyact,yymajor,&yyminorunion); yypParser->yyerrcnt--; if( yyendofinput && yypParser->yyidx>=0 ){ yymajor = 0; }else{ yymajor = YYNOCODE; } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else if( yyact == YY_ERROR_ACTION ){ int yymx; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_shift_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif }else{ yy_accept(yypParser); yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2012 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ const phql_token_names phql_tokens[] = { { PHQL_T_INTEGER, SL("INTEGER") }, { PHQL_T_DOUBLE, SL("DOUBLE") }, { PHQL_T_STRING, SL("STRING") }, { PHQL_T_IDENTIFIER, SL("IDENTIFIER") }, { PHQL_T_MINUS, SL("MINUS") }, { PHQL_T_ADD, SL("+") }, { PHQL_T_SUB, SL("-") }, { PHQL_T_MUL, SL("*") }, { PHQL_T_DIV, SL("/") }, { PHQL_T_BITWISE_AND, SL("&") }, { PHQL_T_BITWISE_OR, SL("|") }, { PHQL_T_MOD, SL("%%") }, { PHQL_T_AND, SL("AND") }, { PHQL_T_OR, SL("OR") }, { PHQL_T_LIKE, SL("LIKE") }, { PHQL_T_DOT, SL("DOT") }, { PHQL_T_COMMA, SL("COMMA") }, { PHQL_T_EQUALS, SL("EQUALS") }, { PHQL_T_NOTEQUALS, SL("NOT EQUALS") }, { PHQL_T_NOT, SL("NOT") }, { PHQL_T_LESS, SL("<") }, { PHQL_T_LESSEQUAL, SL("<=") }, { PHQL_T_GREATER, SL(">") }, { PHQL_T_GREATEREQUAL, SL(">=") }, { PHQL_T_BRACKET_OPEN, SL("(") }, { PHQL_T_BRACKET_CLOSE, SL(")") }, { PHQL_T_NPLACEHOLDER, SL("NUMERIC PLACEHOLDER") }, { PHQL_T_SPLACEHOLDER, SL("STRING PLACEHOLDER") }, { PHQL_T_UPDATE, SL("UPDATE") }, { PHQL_T_SET, SL("SET") }, { PHQL_T_WHERE, SL("WHERE") }, { PHQL_T_DELETE, SL("DELETE") }, { PHQL_T_FROM, SL("FROM") }, { PHQL_T_AS, SL("AS") }, { PHQL_T_INSERT, SL("INSERT") }, { PHQL_T_INTO, SL("INTO") }, { PHQL_T_VALUES, SL("VALUES") }, { PHQL_T_SELECT, SL("SELECT") }, { PHQL_T_ORDER, SL("ORDER") }, { PHQL_T_BY, SL("BY") }, { PHQL_T_LIMIT, SL("LIMIT") }, { PHQL_T_OFFSET, SL("OFFSET") }, { PHQL_T_GROUP, SL("GROUP") }, { PHQL_T_HAVING, SL("HAVING") }, { PHQL_T_IN, SL("IN") }, { PHQL_T_ON, SL("ON") }, { PHQL_T_INNER, SL("INNER") }, { PHQL_T_JOIN, SL("JOIN") }, { PHQL_T_LEFT, SL("LEFT") }, { PHQL_T_RIGHT, SL("RIGHT") }, { PHQL_T_IS, SL("IS") }, { PHQL_T_NULL, SL("NULL") }, { PHQL_T_NOTIN, SL("NOT IN") }, { PHQL_T_CROSS, SL("CROSS") }, { PHQL_T_OUTER, SL("OUTER") }, { PHQL_T_FULL, SL("FULL") }, { PHQL_T_ASC, SL("ASC") }, { PHQL_T_DESC, SL("DESC") }, { PHQL_T_BETWEEN, SL("BETWEEN") }, { PHQL_T_DISTINCT, SL("DISTINCT") }, { 0, NULL, 0 } }; static void *phql_wrapper_alloc(size_t bytes){ return emalloc(bytes); } static void phql_wrapper_free(void *pointer){ efree(pointer); } static void phql_parse_with_token(void* phql_parser, int opcode, int parsercode, phql_scanner_token *token, phql_parser_status *parser_status){ phql_parser_token *pToken; pToken = emalloc(sizeof(phql_parser_token)); pToken->opcode = opcode; pToken->token = token->value; pToken->token_len = token->len; pToken->free_flag = 1; phql_(phql_parser, parsercode, pToken, parser_status); token->value = NULL; token->len = 0; } /** * Creates an error message when it's triggered by the scanner */ static void phql_scanner_error_msg(phql_parser_status *parser_status, zval **error_msg TSRMLS_DC){ char *error, *error_part; unsigned int length; phql_scanner_state *state = parser_status->scanner_state; PHALCON_INIT_VAR(*error_msg); if (state->start) { length = 48 + state->start_length; error = emalloc(sizeof(char) * length); if (state->start_length > 16) { error_part = estrndup(state->start, 16); snprintf(error, length, "Parsing error before '%s...'", error_part); efree(error_part); } else { snprintf(error, length, "Parsing error before '%s'", state->start); } error[length - 1] = '\0'; ZVAL_STRING(*error_msg, error, 1); } else { error = emalloc(sizeof(char) * 48); sprintf(error, "Parsing error near to EOF"); ZVAL_STRING(*error_msg, error, 1); } efree(error); } /** * Executes the internal PHQL parser/tokenizer */ int phql_parse_phql(zval *result, zval *phql TSRMLS_DC){ zval *error_msg = NULL; ZVAL_NULL(result); if(phql_internal_parse_phql(&result, Z_STRVAL_P(phql), Z_STRLEN_P(phql), &error_msg TSRMLS_CC) == FAILURE){ phalcon_throw_exception_string(phalcon_mvc_model_exception_ce, Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg) TSRMLS_CC); return FAILURE; } return SUCCESS; } /** * Executes a PHQL parser/tokenizer */ int phql_internal_parse_phql(zval **result, char *phql, unsigned int phql_length, zval **error_msg TSRMLS_DC) { char *error; phql_scanner_state *state; phql_scanner_token token; int scanner_status, status = SUCCESS; phql_parser_status *parser_status = NULL; void* phql_parser; if (!phql) { PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, "PHQL statement cannot be NULL", 1); return FAILURE; } phql_parser = phql_Alloc(phql_wrapper_alloc); parser_status = emalloc(sizeof(phql_parser_status)); state = emalloc(sizeof(phql_scanner_state)); parser_status->status = PHQL_PARSING_OK; parser_status->scanner_state = state; parser_status->ret = NULL; parser_status->syntax_error = NULL; parser_status->token = &token; state->active_token = 0; state->start = phql; state->start_length = 0; state->end = state->start; token.value = NULL; token.len = 0; while(0 <= (scanner_status = phql_get_token(state, &token))) { /* Calculate the 'start' length */ state->start_length = (phql + phql_length - state->start); state->active_token = token.opcode; /* Parse the token found */ switch(token.opcode){ case PHQL_T_IGNORE: break; case PHQL_T_ADD: phql_(phql_parser, PHQL_PLUS, NULL, parser_status); break; case PHQL_T_SUB: phql_(phql_parser, PHQL_MINUS, NULL, parser_status); break; case PHQL_T_MUL: phql_(phql_parser, PHQL_TIMES, NULL, parser_status); break; case PHQL_T_DIV: phql_(phql_parser, PHQL_DIVIDE, NULL, parser_status); break; case PHQL_T_MOD: phql_(phql_parser, PHQL_MOD, NULL, parser_status); break; case PHQL_T_AND: phql_(phql_parser, PHQL_AND, NULL, parser_status); break; case PHQL_T_OR: phql_(phql_parser, PHQL_OR, NULL, parser_status); break; case PHQL_T_EQUALS: phql_(phql_parser, PHQL_EQUALS, NULL, parser_status); break; case PHQL_T_NOTEQUALS: phql_(phql_parser, PHQL_NOTEQUALS, NULL, parser_status); break; case PHQL_T_LESS: phql_(phql_parser, PHQL_LESS, NULL, parser_status); break; case PHQL_T_GREATER: phql_(phql_parser, PHQL_GREATER, NULL, parser_status); break; case PHQL_T_GREATEREQUAL: phql_(phql_parser, PHQL_GREATEREQUAL, NULL, parser_status); break; case PHQL_T_LESSEQUAL: phql_(phql_parser, PHQL_LESSEQUAL, NULL, parser_status); break; case PHQL_T_LIKE: phql_(phql_parser, PHQL_LIKE, NULL, parser_status); break; case PHQL_T_NOT: phql_(phql_parser, PHQL_NOT, NULL, parser_status); break; case PHQL_T_BITWISE_AND: phql_(phql_parser, PHQL_BITWISE_AND, NULL, parser_status); break; case PHQL_T_BITWISE_OR: phql_(phql_parser, PHQL_BITWISE_OR, NULL, parser_status); break; case PHQL_T_DOT: phql_(phql_parser, PHQL_DOT, NULL, parser_status); break; case PHQL_T_COMMA: phql_(phql_parser, PHQL_COMMA, NULL, parser_status); break; case PHQL_T_BRACKET_OPEN: phql_(phql_parser, PHQL_BRACKET_OPEN, NULL, parser_status); break; case PHQL_T_BRACKET_CLOSE: phql_(phql_parser, PHQL_BRACKET_CLOSE, NULL, parser_status); break; case PHQL_T_INTEGER: phql_parse_with_token(phql_parser, PHQL_T_INTEGER, PHQL_INTEGER, &token, parser_status); break; case PHQL_T_DOUBLE: phql_parse_with_token(phql_parser, PHQL_T_DOUBLE, PHQL_DOUBLE, &token, parser_status); break; case PHQL_T_STRING: phql_parse_with_token(phql_parser, PHQL_T_STRING, PHQL_STRING, &token, parser_status); break; case PHQL_T_IDENTIFIER: phql_parse_with_token(phql_parser, PHQL_T_IDENTIFIER, PHQL_IDENTIFIER, &token, parser_status); break; case PHQL_T_NPLACEHOLDER: phql_parse_with_token(phql_parser, PHQL_T_NPLACEHOLDER, PHQL_NPLACEHOLDER, &token, parser_status); break; case PHQL_T_SPLACEHOLDER: phql_parse_with_token(phql_parser, PHQL_T_SPLACEHOLDER, PHQL_SPLACEHOLDER, &token, parser_status); break; case PHQL_T_FROM: phql_(phql_parser, PHQL_FROM, NULL, parser_status); break; case PHQL_T_UPDATE: phql_(phql_parser, PHQL_UPDATE, NULL, parser_status); break; case PHQL_T_SET: phql_(phql_parser, PHQL_SET, NULL, parser_status); break; case PHQL_T_WHERE: phql_(phql_parser, PHQL_WHERE, NULL, parser_status); break; case PHQL_T_DELETE: phql_(phql_parser, PHQL_DELETE, NULL, parser_status); break; case PHQL_T_INSERT: phql_(phql_parser, PHQL_INSERT, NULL, parser_status); break; case PHQL_T_INTO: phql_(phql_parser, PHQL_INTO, NULL, parser_status); break; case PHQL_T_VALUES: phql_(phql_parser, PHQL_VALUES, NULL, parser_status); break; case PHQL_T_SELECT: phql_(phql_parser, PHQL_SELECT, NULL, parser_status); break; case PHQL_T_AS: phql_(phql_parser, PHQL_AS, NULL, parser_status); break; case PHQL_T_ORDER: phql_(phql_parser, PHQL_ORDER, NULL, parser_status); break; case PHQL_T_BY: phql_(phql_parser, PHQL_BY, NULL, parser_status); break; case PHQL_T_LIMIT: phql_(phql_parser, PHQL_LIMIT, NULL, parser_status); break; case PHQL_T_OFFSET: phql_(phql_parser, PHQL_OFFSET, NULL, parser_status); break; case PHQL_T_GROUP: phql_(phql_parser, PHQL_GROUP, NULL, parser_status); break; case PHQL_T_HAVING: phql_(phql_parser, PHQL_HAVING, NULL, parser_status); break; case PHQL_T_ASC: phql_(phql_parser, PHQL_ASC, NULL, parser_status); break; case PHQL_T_DESC: phql_(phql_parser, PHQL_DESC, NULL, parser_status); break; case PHQL_T_IN: phql_(phql_parser, PHQL_IN, NULL, parser_status); break; case PHQL_T_ON: phql_(phql_parser, PHQL_ON, NULL, parser_status); break; case PHQL_T_INNER: phql_(phql_parser, PHQL_INNER, NULL, parser_status); break; case PHQL_T_JOIN: phql_(phql_parser, PHQL_JOIN, NULL, parser_status); break; case PHQL_T_LEFT: phql_(phql_parser, PHQL_LEFT, NULL, parser_status); break; case PHQL_T_RIGHT: phql_(phql_parser, PHQL_RIGHT, NULL, parser_status); break; case PHQL_T_CROSS: phql_(phql_parser, PHQL_CROSS, NULL, parser_status); break; case PHQL_T_FULL: phql_(phql_parser, PHQL_FULL, NULL, parser_status); break; case PHQL_T_OUTER: phql_(phql_parser, PHQL_OUTER, NULL, parser_status); break; case PHQL_T_IS: phql_(phql_parser, PHQL_IS, NULL, parser_status); break; case PHQL_T_NULL: phql_(phql_parser, PHQL_NULL, NULL, parser_status); break; case PHQL_T_BETWEEN: phql_(phql_parser, PHQL_BETWEEN, NULL, parser_status); break; case PHQL_T_DISTINCT: phql_(phql_parser, PHQL_DISTINCT, NULL, parser_status); break; default: parser_status->status = PHQL_PARSING_FAILED; error = emalloc(sizeof(char) * 32); sprintf(error, "scanner: unknown opcode %c", token.opcode); PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, error, 1); efree(error); break; } if (parser_status->status != PHQL_PARSING_OK) { status = FAILURE; break; } state->end = state->start; } if (status != FAILURE) { switch (scanner_status) { case PHQL_SCANNER_RETCODE_ERR: case PHQL_SCANNER_RETCODE_IMPOSSIBLE: if (!*error_msg) { if (!*error_msg) { phql_scanner_error_msg(parser_status, error_msg TSRMLS_CC); } } status = FAILURE; break; default: phql_(phql_parser, 0, NULL, parser_status); } } state->active_token = 0; state->start = NULL; if (parser_status->status != PHQL_PARSING_OK) { status = FAILURE; if (parser_status->syntax_error) { if (!*error_msg) { PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, parser_status->syntax_error, 1); } efree(parser_status->syntax_error); } } phql_Free(phql_parser, phql_wrapper_free); if (status != FAILURE) { if (parser_status->status == PHQL_PARSING_OK) { if (parser_status->ret) { ZVAL_ZVAL(*result, parser_status->ret, 0, 0); ZVAL_NULL(parser_status->ret); zval_ptr_dtor(&parser_status->ret); } else { efree(parser_status->ret); } } } efree(parser_status); efree(state); return status; }
tmihalik/cphalcon
ext/kernel/experimental/fcall.h
<filename>ext/kernel/experimental/fcall.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern int phalcon_exp_call_user_method(zend_class_entry *ce, zval **object_pp, zval *function_name, zval *retval_ptr, zend_uint param_count, zval *params[], unsigned long method_key TSRMLS_DC); int phalcon_exp_call_user_method_ex(zend_class_entry *ce, zval **object_pp, zval *method_name, zval **retval_ptr_ptr, zend_uint param_count, zval **params[], unsigned long method_key TSRMLS_DC); int phalcon_exp_call_method(zend_fcall_info *fci, zend_class_entry *ce, char *key, unsigned int key_length, unsigned long hash_key, unsigned long method_key TSRMLS_DC);
tmihalik/cphalcon
ext/mvc/model/resultset/simple.h
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_model_resultset_simple_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Resultset_Simple); PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, __construct); PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, valid); PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, toArray); PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, serialize); PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, unserialize); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_resultset_simple___construct, 0, 0, 3) ZEND_ARG_INFO(0, columnMap) ZEND_ARG_INFO(0, model) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, cache) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_resultset_simple_unserialize, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_model_resultset_simple_method_entry){ PHP_ME(Phalcon_Mvc_Model_Resultset_Simple, __construct, arginfo_phalcon_mvc_model_resultset_simple___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Mvc_Model_Resultset_Simple, valid, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Resultset_Simple, toArray, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Resultset_Simple, serialize, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Model_Resultset_Simple, unserialize, arginfo_phalcon_mvc_model_resultset_simple_unserialize, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/cache/frontend/none.h
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_cache_frontend_none_ce; PHALCON_INIT_CLASS(Phalcon_Cache_Frontend_None); PHP_METHOD(Phalcon_Cache_Frontend_None, __construct); PHP_METHOD(Phalcon_Cache_Frontend_None, getLifetime); PHP_METHOD(Phalcon_Cache_Frontend_None, isBuffering); PHP_METHOD(Phalcon_Cache_Frontend_None, start); PHP_METHOD(Phalcon_Cache_Frontend_None, getContent); PHP_METHOD(Phalcon_Cache_Frontend_None, stop); PHP_METHOD(Phalcon_Cache_Frontend_None, beforeStore); PHP_METHOD(Phalcon_Cache_Frontend_None, afterRetrieve); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_cache_frontend_none___construct, 0, 0, 0) ZEND_ARG_INFO(0, frontendOptions) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_cache_frontend_none_beforestore, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_cache_frontend_none_afterretrieve, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_cache_frontend_none_method_entry){ PHP_ME(Phalcon_Cache_Frontend_None, __construct, arginfo_phalcon_cache_frontend_none___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Cache_Frontend_None, getLifetime, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, isBuffering, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, start, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, getContent, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, stop, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, beforeStore, arginfo_phalcon_cache_frontend_none_beforestore, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Cache_Frontend_None, afterRetrieve, arginfo_phalcon_cache_frontend_none_afterretrieve, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/http/request/file.c
<reponame>tmihalik/cphalcon<filename>ext/http/request/file.c<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/exception.h" #include "kernel/array.h" #include "kernel/object.h" #include "kernel/fcall.h" /** * Phalcon\Http\Request\File * * Provides OO wrappers to the $_FILES superglobal * *<code> * class PostsController extends \Phalcon\Mvc\Controller * { * * public function uploadAction() * { * //Check if the user has uploaded files * if ($this->request->hasFiles() == true) { * //Print the real file names and their sizes * foreach ($this->request->getUploadedFiles() as $file){ * echo $file->getName(), " ", $file->getSize(), "\n"; * } * } * } * * } *</code> */ /** * Phalcon\Http\Request\File initializer */ PHALCON_INIT_CLASS(Phalcon_Http_Request_File){ PHALCON_REGISTER_CLASS(Phalcon\\Http\\Request, File, http_request_file, phalcon_http_request_file_method_entry, 0); zend_declare_property_null(phalcon_http_request_file_ce, SL("_name"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_http_request_file_ce, SL("_tmp"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_http_request_file_ce, SL("_size"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_http_request_file_ce TSRMLS_CC, 1, phalcon_http_request_fileinterface_ce); return SUCCESS; } /** * Phalcon\Http\Request\File constructor * * @param array $file */ PHP_METHOD(Phalcon_Http_Request_File, __construct){ zval *file, *name, *temp_name, *size; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &file) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(file) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_http_request_exception_ce, "Phalcon\\Http\\Request\\File requires a valid uploaded file"); return; } if (phalcon_array_isset_string(file, SS("name"))) { PHALCON_OBS_VAR(name); phalcon_array_fetch_string(&name, file, SL("name"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_name"), name TSRMLS_CC); } if (phalcon_array_isset_string(file, SS("tmp_name"))) { PHALCON_OBS_VAR(temp_name); phalcon_array_fetch_string(&temp_name, file, SL("tmp_name"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_tmp"), temp_name TSRMLS_CC); } if (phalcon_array_isset_string(file, SS("size"))) { PHALCON_OBS_VAR(size); phalcon_array_fetch_string(&size, file, SL("size"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_size"), size TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Returns the file size of the uploaded file * * @return int */ PHP_METHOD(Phalcon_Http_Request_File, getSize){ RETURN_MEMBER(this_ptr, "_size"); } /** * Returns the real name of the uploaded file * * @return string */ PHP_METHOD(Phalcon_Http_Request_File, getName){ RETURN_MEMBER(this_ptr, "_name"); } /** * Returns the temporal name of the uploaded file * * @return string */ PHP_METHOD(Phalcon_Http_Request_File, getTempName){ RETURN_MEMBER(this_ptr, "_tmp"); } /** * Move the temporary file to a destination whithin the application * * @param string $destination * @return boolean */ PHP_METHOD(Phalcon_Http_Request_File, moveTo){ zval *destination, *temp_file, *success; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &destination) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(temp_file); phalcon_read_property(&temp_file, this_ptr, SL("_tmp"), PH_NOISY_CC); PHALCON_INIT_VAR(success); PHALCON_CALL_FUNC_PARAMS_2(success, "move_uploaded_file", temp_file, destination); RETURN_CCTOR(success); }
tmihalik/cphalcon
ext/db/adapter/pdo.h
<filename>ext/db/adapter/pdo.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_db_adapter_pdo_ce; PHALCON_INIT_CLASS(Phalcon_Db_Adapter_Pdo); PHP_METHOD(Phalcon_Db_Adapter_Pdo, __construct); PHP_METHOD(Phalcon_Db_Adapter_Pdo, connect); PHP_METHOD(Phalcon_Db_Adapter_Pdo, executePrepared); PHP_METHOD(Phalcon_Db_Adapter_Pdo, query); PHP_METHOD(Phalcon_Db_Adapter_Pdo, execute); PHP_METHOD(Phalcon_Db_Adapter_Pdo, affectedRows); PHP_METHOD(Phalcon_Db_Adapter_Pdo, close); PHP_METHOD(Phalcon_Db_Adapter_Pdo, escapeIdentifier); PHP_METHOD(Phalcon_Db_Adapter_Pdo, escapeString); PHP_METHOD(Phalcon_Db_Adapter_Pdo, bindParams); PHP_METHOD(Phalcon_Db_Adapter_Pdo, convertBoundParams); PHP_METHOD(Phalcon_Db_Adapter_Pdo, lastInsertId); PHP_METHOD(Phalcon_Db_Adapter_Pdo, begin); PHP_METHOD(Phalcon_Db_Adapter_Pdo, rollback); PHP_METHOD(Phalcon_Db_Adapter_Pdo, commit); PHP_METHOD(Phalcon_Db_Adapter_Pdo, isUnderTransaction); PHP_METHOD(Phalcon_Db_Adapter_Pdo, getInternalHandler); PHP_METHOD(Phalcon_Db_Adapter_Pdo, describeIndexes); PHP_METHOD(Phalcon_Db_Adapter_Pdo, describeReferences); PHP_METHOD(Phalcon_Db_Adapter_Pdo, tableOptions); PHP_METHOD(Phalcon_Db_Adapter_Pdo, getDefaultIdValue); PHP_METHOD(Phalcon_Db_Adapter_Pdo, supportSequences); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo___construct, 0, 0, 1) ZEND_ARG_INFO(0, descriptor) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_connect, 0, 0, 0) ZEND_ARG_INFO(0, descriptor) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_executeprepared, 0, 0, 3) ZEND_ARG_INFO(0, statement) ZEND_ARG_INFO(0, placeholders) ZEND_ARG_INFO(0, dataTypes) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_query, 0, 0, 1) ZEND_ARG_INFO(0, sqlStatement) ZEND_ARG_INFO(0, bindParams) ZEND_ARG_INFO(0, bindTypes) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_execute, 0, 0, 1) ZEND_ARG_INFO(0, sqlStatement) ZEND_ARG_INFO(0, bindParams) ZEND_ARG_INFO(0, bindTypes) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_escapeidentifier, 0, 0, 1) ZEND_ARG_INFO(0, identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_escapestring, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_bindparams, 0, 0, 2) ZEND_ARG_INFO(0, sqlStatement) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_convertboundparams, 0, 0, 2) ZEND_ARG_INFO(0, sql) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_lastinsertid, 0, 0, 0) ZEND_ARG_INFO(0, sequenceName) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_describeindexes, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_describereferences, 0, 0, 1) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, schema) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_adapter_pdo_tableoptions, 0, 0, 1) ZEND_ARG_INFO(0, tableName) ZEND_ARG_INFO(0, schemaName) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_db_adapter_pdo_method_entry){ PHP_ME(Phalcon_Db_Adapter_Pdo, __construct, arginfo_phalcon_db_adapter_pdo___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Db_Adapter_Pdo, connect, arginfo_phalcon_db_adapter_pdo_connect, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, executePrepared, arginfo_phalcon_db_adapter_pdo_executeprepared, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, query, arginfo_phalcon_db_adapter_pdo_query, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, execute, arginfo_phalcon_db_adapter_pdo_execute, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, affectedRows, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, close, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, escapeIdentifier, arginfo_phalcon_db_adapter_pdo_escapeidentifier, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, escapeString, arginfo_phalcon_db_adapter_pdo_escapestring, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, bindParams, arginfo_phalcon_db_adapter_pdo_bindparams, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, convertBoundParams, arginfo_phalcon_db_adapter_pdo_convertboundparams, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, lastInsertId, arginfo_phalcon_db_adapter_pdo_lastinsertid, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, begin, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, rollback, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, commit, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, isUnderTransaction, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, getInternalHandler, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, describeIndexes, arginfo_phalcon_db_adapter_pdo_describeindexes, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, describeReferences, arginfo_phalcon_db_adapter_pdo_describereferences, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, tableOptions, arginfo_phalcon_db_adapter_pdo_tableoptions, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, getDefaultIdValue, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_Adapter_Pdo, supportSequences, NULL, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/security.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/exception.h" #include "kernel/operators.h" #include "kernel/fcall.h" #include "kernel/filter.h" #include "kernel/string.h" #include "kernel/concat.h" /** * Phalcon\Security * * This component provides a set of functions to improve the security in Phalcon applications * */ /** * Phalcon\Security initializer */ PHALCON_INIT_CLASS(Phalcon_Security){ PHALCON_REGISTER_CLASS(Phalcon, Security, security, phalcon_security_method_entry, 0); zend_declare_property_null(phalcon_security_ce, SL("_dependencyInjector"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_security_ce, SL("_workFactor"), 8, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_long(phalcon_security_ce, SL("_numberBytes"), 16, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_security_ce, SL("_csrf"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_security_ce TSRMLS_CC, 1, phalcon_di_injectionawareinterface_ce); return SUCCESS; } /** * Sets the dependency injector * * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Security, setDI){ zval *dependency_injector; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &dependency_injector) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); } /** * Returns the internal dependency injector * * @return Phalcon\DiInterface */ PHP_METHOD(Phalcon_Security, getDI){ RETURN_MEMBER(this_ptr, "_dependencyInjector"); } /** * Sets a number of bytes to be generated by the openssl pseudo random generator * * @param string $randomBytes */ PHP_METHOD(Phalcon_Security, setRandomBytes){ zval *random_bytes, *sixteen, *minimum_bytes; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &random_bytes) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(random_bytes) != IS_LONG) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "Random bytes must be integer"); return; } PHALCON_INIT_VAR(sixteen); ZVAL_LONG(sixteen, 16); PHALCON_INIT_VAR(minimum_bytes); is_smaller_function(minimum_bytes, random_bytes, sixteen TSRMLS_CC); if (PHALCON_IS_TRUE(minimum_bytes)) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "At least 16 bytes are needed to produce a correct salt"); return; } phalcon_update_property_zval(this_ptr, SL("_numberBytes"), random_bytes TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns a number of bytes to be generated by the openssl pseudo random generator * * @return string */ PHP_METHOD(Phalcon_Security, getRandomBytes){ RETURN_MEMBER(this_ptr, "_numberBytes"); } /** * Sets the default working factor for bcrypts password's salts * * @param int $workFactor */ PHP_METHOD(Phalcon_Security, setWorkFactor){ zval *work_factor; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &work_factor) == FAILURE) { RETURN_MM_NULL(); } if (Z_TYPE_P(work_factor) != IS_LONG) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "Work factor must be integer"); return; } phalcon_update_property_zval(this_ptr, SL("_workFactor"), work_factor TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the default working factor for bcrypts password's salts * * @return int */ PHP_METHOD(Phalcon_Security, getWorkFactor){ RETURN_MEMBER(this_ptr, "_workFactor"); } /** * Generate a >22-length pseudo random string to be used as salt for passwords * * @return string */ PHP_METHOD(Phalcon_Security, getSaltBytes){ zval *twenty_two, *number_bytes, *random_bytes = NULL; zval *base64bytes = NULL, *safe_bytes = NULL, *bytes_length = NULL; zval *minimum_bytes = NULL; PHALCON_MM_GROW(); if (phalcon_function_exists_ex(SS("openssl_random_pseudo_bytes") TSRMLS_CC) == FAILURE) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "Openssl extension must be loaded"); return; } PHALCON_INIT_VAR(twenty_two); ZVAL_LONG(twenty_two, 22); PHALCON_OBS_VAR(number_bytes); phalcon_read_property(&number_bytes, this_ptr, SL("_numberBytes"), PH_NOISY_CC); while (1) { PHALCON_INIT_NVAR(random_bytes); PHALCON_CALL_FUNC_PARAMS_1(random_bytes, "openssl_random_pseudo_bytes", number_bytes); PHALCON_INIT_NVAR(base64bytes); PHALCON_CALL_FUNC_PARAMS_1(base64bytes, "base64_encode", random_bytes); PHALCON_INIT_NVAR(safe_bytes); phalcon_filter_alphanum(safe_bytes, base64bytes); if (!zend_is_true(safe_bytes)) { continue; } PHALCON_INIT_NVAR(bytes_length); phalcon_fast_strlen(bytes_length, safe_bytes); PHALCON_INIT_NVAR(minimum_bytes); is_smaller_function(minimum_bytes, bytes_length, twenty_two TSRMLS_CC); if (PHALCON_IS_TRUE(minimum_bytes)) { continue; } break; } RETURN_CTOR(safe_bytes); } /** * Creates a password hash using bcrypt with a pseudo random salt * * @param string $password * @param int $workFactor * @return string */ PHP_METHOD(Phalcon_Security, hash){ zval *password, *work_factor = NULL, *format, *factor; zval *salt_bytes, *salt, *hash; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &password, &work_factor) == FAILURE) { RETURN_MM_NULL(); } if (!work_factor) { PHALCON_INIT_VAR(work_factor); } else { PHALCON_SEPARATE_PARAM(work_factor); } if (Z_TYPE_P(work_factor) == IS_NULL) { PHALCON_OBS_NVAR(work_factor); phalcon_read_property(&work_factor, this_ptr, SL("_workFactor"), PH_NOISY_CC); } PHALCON_INIT_VAR(format); ZVAL_STRING(format, "%02s", 1); PHALCON_INIT_VAR(factor); PHALCON_CALL_FUNC_PARAMS_2(factor, "sprintf", format, work_factor); PHALCON_INIT_VAR(salt_bytes); PHALCON_CALL_METHOD(salt_bytes, this_ptr, "getsaltbytes"); PHALCON_INIT_VAR(salt); PHALCON_CONCAT_SVSV(salt, "$2a$", factor, "$", salt_bytes); PHALCON_INIT_VAR(hash); PHALCON_CALL_FUNC_PARAMS_2(hash, "crypt", password, salt); RETURN_CCTOR(hash); } /** * Checks a plain text password and its hash version to check if the password matches * * @param string $password * @param string $passwordHash * @return boolean */ PHP_METHOD(Phalcon_Security, checkHash){ zval *password, *password_hash, *hash, *are_equals; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &password, &password_hash) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(hash); PHALCON_CALL_FUNC_PARAMS_2(hash, "crypt", password, password_hash); PHALCON_INIT_VAR(are_equals); is_equal_function(are_equals, hash, password_hash TSRMLS_CC); RETURN_NCTOR(are_equals); } /** * Checks a plain text password and its hash version to check if the password matches * * @param string $password * @param string $passwordHash * @return boolean */ PHP_METHOD(Phalcon_Security, isLegacyHash){ zval *password_hash; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &password_hash) == FAILURE) { RETURN_NULL(); } if (phalcon_start_with_str(password_hash, SL("<PASSWORD>$"))) { RETURN_TRUE; } RETURN_FALSE; } /** * Generates a pseudo random token key to be used as input's name in a CSRF check * * @param int $numberBytes * @return string */ PHP_METHOD(Phalcon_Security, getTokenKey){ zval *number_bytes = NULL, *random_bytes, *base64bytes; zval *safe_bytes, *dependency_injector, *service; zval *session, *key; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &number_bytes) == FAILURE) { RETURN_MM_NULL(); } if (!number_bytes) { PHALCON_INIT_VAR(number_bytes); ZVAL_LONG(number_bytes, 12); } if (phalcon_function_exists_ex(SS("openssl_random_pseudo_bytes") TSRMLS_CC) == FAILURE) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "Openssl extension must be loaded"); return; } PHALCON_INIT_VAR(random_bytes); PHALCON_CALL_FUNC_PARAMS_1(random_bytes, "openssl_random_pseudo_bytes", number_bytes); PHALCON_INIT_VAR(base64bytes); PHALCON_CALL_FUNC_PARAMS_1(base64bytes, "base64_encode", random_bytes); PHALCON_INIT_VAR(safe_bytes); phalcon_filter_alphanum(safe_bytes, base64bytes); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_flash_exception_ce, "A dependency injection container is required to access the 'session' service"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "session", 1); PHALCON_INIT_VAR(session); PHALCON_CALL_METHOD_PARAMS_1(session, dependency_injector, "getshared", service); PHALCON_INIT_VAR(key); ZVAL_STRING(key, "$PHALCON/CSRF/KEY$", 1); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(session, "set", key, safe_bytes); RETURN_CTOR(safe_bytes); } /** * Generates a pseudo random token value to be used as input's value in a CSRF check * * @param int $numberBytes * @return string */ PHP_METHOD(Phalcon_Security, getToken){ zval *number_bytes = NULL, *random_bytes, *token, *dependency_injector; zval *service, *session, *key; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z", &number_bytes) == FAILURE) { RETURN_MM_NULL(); } if (!number_bytes) { PHALCON_INIT_VAR(number_bytes); ZVAL_LONG(number_bytes, 12); } if (phalcon_function_exists_ex(SS("openssl_random_pseudo_bytes") TSRMLS_CC) == FAILURE) { PHALCON_THROW_EXCEPTION_STR(phalcon_security_exception_ce, "Openssl extension must be loaded"); return; } PHALCON_INIT_VAR(random_bytes); PHALCON_CALL_FUNC_PARAMS_1(random_bytes, "openssl_random_pseudo_bytes", number_bytes); PHALCON_INIT_VAR(token); PHALCON_CALL_FUNC_PARAMS_1(token, "md5", random_bytes); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_flash_exception_ce, "A dependency injection container is required to access the 'session' service"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "session", 1); PHALCON_INIT_VAR(session); PHALCON_CALL_METHOD_PARAMS_1(session, dependency_injector, "getshared", service); PHALCON_INIT_VAR(key); ZVAL_STRING(key, "$PHALCON/CSRF$", 1); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(session, "set", key, token); RETURN_CCTOR(token); } /** * Check if the CSRF token sent in the request is the same that the current in session * * @param string $tokenKey * @param string $tokenValue * @return boolean */ PHP_METHOD(Phalcon_Security, checkToken){ zval *token_key = NULL, *token_value = NULL, *dependency_injector; zval *service = NULL, *session, *key = NULL, *request, *token = NULL, *session_token; zval *same; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &token_key, &token_value) == FAILURE) { RETURN_MM_NULL(); } if (!token_key) { PHALCON_INIT_VAR(token_key); } else { PHALCON_SEPARATE_PARAM(token_key); } if (!token_value) { PHALCON_INIT_VAR(token_value); } PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_flash_exception_ce, "A dependency injection container is required to access the 'session' service"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "session", 1); PHALCON_INIT_VAR(session); PHALCON_CALL_METHOD_PARAMS_1(session, dependency_injector, "getshared", service); if (Z_TYPE_P(token_key) == IS_NULL) { PHALCON_INIT_VAR(key); ZVAL_STRING(key, "$PHALCON/CSRF/KEY$", 1); PHALCON_INIT_NVAR(token_key); PHALCON_CALL_METHOD_PARAMS_1(token_key, session, "get", key); } if (Z_TYPE_P(token_value) == IS_NULL) { PHALCON_INIT_NVAR(service); ZVAL_STRING(service, "request", 1); PHALCON_INIT_VAR(request); PHALCON_CALL_METHOD_PARAMS_1(request, dependency_injector, "getshared", service); /** * We always check if the value is correct in post */ PHALCON_INIT_VAR(token); PHALCON_CALL_METHOD_PARAMS_1(token, request, "getpost", token_key); } else { PHALCON_CPY_WRT(token, token_value); } PHALCON_INIT_NVAR(key); ZVAL_STRING(key, "$PHALCON/CSRF$", 1); PHALCON_INIT_VAR(session_token); PHALCON_CALL_METHOD_PARAMS_1(session_token, session, "get", key); /** * The value is the same? */ PHALCON_INIT_VAR(same); is_equal_function(same, token, session_token TSRMLS_CC); RETURN_NCTOR(same); } /** * Returns the value of the CSRF token in session * * @return string */ PHP_METHOD(Phalcon_Security, getSessionToken){ zval *dependency_injector, *service, *session; zval *key, *session_token; PHALCON_MM_GROW(); PHALCON_OBS_VAR(dependency_injector); phalcon_read_property(&dependency_injector, this_ptr, SL("_dependencyInjector"), PH_NOISY_CC); if (Z_TYPE_P(dependency_injector) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_flash_exception_ce, "A dependency injection container is required to access the 'session' service"); return; } PHALCON_INIT_VAR(service); ZVAL_STRING(service, "session", 1); PHALCON_INIT_VAR(session); PHALCON_CALL_METHOD_PARAMS_1(session, dependency_injector, "getshared", service); PHALCON_INIT_VAR(key); ZVAL_STRING(key, "$PHALCON/CSRF$", 1); PHALCON_INIT_VAR(session_token); PHALCON_CALL_METHOD_PARAMS_1(session_token, session, "get", key); RETURN_CCTOR(session_token); }
tmihalik/cphalcon
ext/events/event.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/operators.h" #include "kernel/exception.h" /** * Phalcon\Events\Event * * This class offers contextual information of a fired event in the EventsManager */ /** * Phalcon\Events\Event initializer */ PHALCON_INIT_CLASS(Phalcon_Events_Event){ PHALCON_REGISTER_CLASS(Phalcon\\Events, Event, events_event, phalcon_events_event_method_entry, 0); zend_declare_property_null(phalcon_events_event_ce, SL("_type"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_events_event_ce, SL("_source"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_events_event_ce, SL("_data"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_events_event_ce, SL("_stopped"), 0, ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_bool(phalcon_events_event_ce, SL("_cancelable"), 1, ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } /** * Phalcon\Events\Event constructor * * @param string $type * @param object $source * @param mixed $data * @param boolean $cancelable */ PHP_METHOD(Phalcon_Events_Event, __construct){ zval *type, *source, *data = NULL, *cancelable = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz|zz", &type, &source, &data, &cancelable) == FAILURE) { RETURN_MM_NULL(); } if (!data) { PHALCON_INIT_VAR(data); } if (!cancelable) { PHALCON_INIT_VAR(cancelable); ZVAL_BOOL(cancelable, 1); } phalcon_update_property_zval(this_ptr, SL("_type"), type TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_source"), source TSRMLS_CC); if (Z_TYPE_P(data) != IS_NULL) { phalcon_update_property_zval(this_ptr, SL("_data"), data TSRMLS_CC); } if (PHALCON_IS_NOT_TRUE(cancelable)) { phalcon_update_property_zval(this_ptr, SL("_cancelable"), cancelable TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Set the event's type * * @param string $eventType */ PHP_METHOD(Phalcon_Events_Event, setType){ zval *event_type; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &event_type) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_type"), event_type TSRMLS_CC); } /** * Returns the event's type * * @return string */ PHP_METHOD(Phalcon_Events_Event, getType){ RETURN_MEMBER(this_ptr, "_type"); } /** * Returns the event's source * * @return object */ PHP_METHOD(Phalcon_Events_Event, getSource){ RETURN_MEMBER(this_ptr, "_source"); } /** * Set the event's data * * @param string $data */ PHP_METHOD(Phalcon_Events_Event, setData){ zval *data; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_data"), data TSRMLS_CC); } /** * Returns the event's data * * @return mixed */ PHP_METHOD(Phalcon_Events_Event, getData){ RETURN_MEMBER(this_ptr, "_data"); } /** * Sets if the event is cancelable * * @param boolean $cancelable */ PHP_METHOD(Phalcon_Events_Event, setCancelable){ zval *cancelable; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &cancelable) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_cancelable"), cancelable TSRMLS_CC); } /** * Check whether the event is cancelable * * @return boolean */ PHP_METHOD(Phalcon_Events_Event, getCancelable){ RETURN_MEMBER(this_ptr, "_cancelable"); } /** * Stops the event preventing propagation */ PHP_METHOD(Phalcon_Events_Event, stop){ zval *cancelable; PHALCON_MM_GROW(); PHALCON_OBS_VAR(cancelable); phalcon_read_property(&cancelable, this_ptr, SL("_cancelable"), PH_NOISY_CC); if (zend_is_true(cancelable)) { phalcon_update_property_bool(this_ptr, SL("_stopped"), 1 TSRMLS_CC); } else { PHALCON_THROW_EXCEPTION_STR(phalcon_events_exception_ce, "Trying to cancel a non-cancelable event"); return; } PHALCON_MM_RESTORE(); } /** * Check whether the event is currently stopped */ PHP_METHOD(Phalcon_Events_Event, isStopped){ RETURN_MEMBER(this_ptr, "_stopped"); }
tmihalik/cphalcon
ext/http/response/headers.c
<filename>ext/http/response/headers.c /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/fcall.h" #include "kernel/concat.h" /** * Phalcon\Http\Response\Headers * * This class is a bag to manage the response headers */ /** * Phalcon\Http\Response\Headers initializer */ PHALCON_INIT_CLASS(Phalcon_Http_Response_Headers){ PHALCON_REGISTER_CLASS(Phalcon\\Http\\Response, Headers, http_response_headers, phalcon_http_response_headers_method_entry, 0); zend_declare_property_null(phalcon_http_response_headers_ce, SL("_headers"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_http_response_headers_ce TSRMLS_CC, 1, phalcon_http_response_headersinterface_ce); return SUCCESS; } /** * Phalcon\Http\Response\Headers constructor */ PHP_METHOD(Phalcon_Http_Response_Headers, __construct){ phalcon_update_property_empty_array(phalcon_http_response_headers_ce, this_ptr, SL("_headers") TSRMLS_CC); } /** * Sets a header to be sent at the end of the request * * @param string $name * @param string $value */ PHP_METHOD(Phalcon_Http_Response_Headers, set){ zval *name, *value; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &name, &value) == FAILURE) { RETURN_NULL(); } phalcon_update_property_array(this_ptr, SL("_headers"), name, value TSRMLS_CC); } /** * Gets a header value from the internal bag * * @param string $name * @return string */ PHP_METHOD(Phalcon_Http_Response_Headers, get){ zval *name, *headers, *header_value; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &name) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(headers); phalcon_read_property(&headers, this_ptr, SL("_headers"), PH_NOISY_CC); if (phalcon_array_isset(headers, name)) { PHALCON_OBS_VAR(header_value); phalcon_array_fetch(&header_value, headers, name, PH_NOISY_CC); RETURN_CCTOR(header_value); } RETURN_MM_FALSE; } /** * Sets a raw header to be sent at the end of the request * * @param string $header */ PHP_METHOD(Phalcon_Http_Response_Headers, setRaw){ zval *header; zval *t0 = NULL; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &header) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(t0); ZVAL_BOOL(t0, 0); phalcon_update_property_array(this_ptr, SL("_headers"), header, t0 TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Sends the headers to the client * * @return boolean */ PHP_METHOD(Phalcon_Http_Response_Headers, send){ zval *headers_was_sent, *t, *headers, *value = NULL, *header = NULL; zval *http_header = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); PHALCON_INIT_VAR(headers_was_sent); PHALCON_CALL_FUNC(headers_was_sent, "headers_sent"); if (!zend_is_true(headers_was_sent)) { PHALCON_INIT_VAR(t); ZVAL_BOOL(t, 1); PHALCON_OBS_VAR(headers); phalcon_read_property(&headers, this_ptr, SL("_headers"), PH_NOISY_CC); if (!phalcon_is_iterable(headers, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(header, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); if (zend_is_true(value)) { PHALCON_INIT_NVAR(http_header); PHALCON_CONCAT_VSV(http_header, header, ": ", value); PHALCON_CALL_FUNC_PARAMS_2_NORETURN("header", http_header, t); } else { PHALCON_CALL_FUNC_PARAMS_2_NORETURN("header", header, t); } zend_hash_move_forward_ex(ah0, &hp0); } RETURN_MM_TRUE; } RETURN_MM_FALSE; } /** * Reset set headers * */ PHP_METHOD(Phalcon_Http_Response_Headers, reset){ zval *empty_array; PHALCON_MM_GROW(); PHALCON_INIT_VAR(empty_array); array_init(empty_array); phalcon_update_property_zval(this_ptr, SL("_headers"), empty_array TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Restore a Phalcon\Http\Response\Headers object * * @param array $data * @return Phalcon\Http\Response\Headers */ PHP_METHOD(Phalcon_Http_Response_Headers, __set_state){ zval *data, *headers, *data_headers, *value = NULL, *key = NULL; HashTable *ah0; HashPosition hp0; zval **hd; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(headers); object_init_ex(headers, phalcon_http_response_headers_ce); PHALCON_CALL_METHOD_NORETURN(headers, "__construct"); if (phalcon_array_isset_string(data, SS("_headers"))) { PHALCON_OBS_VAR(data_headers); phalcon_array_fetch_string(&data_headers, data, SL("_headers"), PH_NOISY_CC); if (!phalcon_is_iterable(data_headers, &ah0, &hp0, 0, 0 TSRMLS_CC)) { return; } while (zend_hash_get_current_data_ex(ah0, (void**) &hd, &hp0) == SUCCESS) { PHALCON_GET_FOREACH_KEY(key, ah0, hp0); PHALCON_GET_FOREACH_VALUE(value); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(headers, "set", key, value); zend_hash_move_forward_ex(ah0, &hp0); } } RETURN_CTOR(headers); }
tmihalik/cphalcon
ext/paginator/adapter/model.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/operators.h" #include "kernel/exception.h" #include "kernel/fcall.h" /** * Phalcon\Paginator\Adapter\Model * * This adapter allows to paginate data using a Phalcon\Mvc\Model resultset as base */ /** * Phalcon\Paginator\Adapter\Model initializer */ PHALCON_INIT_CLASS(Phalcon_Paginator_Adapter_Model){ PHALCON_REGISTER_CLASS(Phalcon\\Paginator\\Adapter, Model, paginator_adapter_model, phalcon_paginator_adapter_model_method_entry, 0); zend_declare_property_null(phalcon_paginator_adapter_model_ce, SL("_limitRows"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_paginator_adapter_model_ce, SL("_config"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_paginator_adapter_model_ce, SL("_page"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_paginator_adapter_model_ce TSRMLS_CC, 1, phalcon_paginator_adapterinterface_ce); return SUCCESS; } /** * Phalcon\Paginator\Adapter\Model constructor * * @param array $config */ PHP_METHOD(Phalcon_Paginator_Adapter_Model, __construct){ zval *config, *limit, *page; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &config) == FAILURE) { RETURN_MM_NULL(); } phalcon_update_property_zval(this_ptr, SL("_config"), config TSRMLS_CC); if (phalcon_array_isset_string(config, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, config, SL("limit"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_limitRows"), limit TSRMLS_CC); } if (phalcon_array_isset_string(config, SS("page"))) { PHALCON_OBS_VAR(page); phalcon_array_fetch_string(&page, config, SL("page"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_page"), page TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Set the current page number * * @param int $page */ PHP_METHOD(Phalcon_Paginator_Adapter_Model, setCurrentPage){ zval *page; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &page) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_page"), page TSRMLS_CC); } /** * Returns a slice of the resultset to show in the pagination * * @return stdClass */ PHP_METHOD(Phalcon_Paginator_Adapter_Model, getPaginate){ zval *one, *zero, *show, *config, *items, *page_number = NULL; zval *smaller, *n, *page, *last_show_page, *start; zval *last_page, *possible_pages = NULL, *total_pages; zval *compare = NULL, *page_items, *i, *valid = NULL, *current = NULL, *maximum_pages; zval *next = NULL, *additional_page, *before = NULL, *remainder; zval *pages_total = NULL; zval *r0 = NULL; PHALCON_MM_GROW(); PHALCON_INIT_VAR(one); ZVAL_LONG(one, 1); PHALCON_INIT_VAR(zero); ZVAL_LONG(zero, 0); PHALCON_OBS_VAR(show); phalcon_read_property(&show, this_ptr, SL("_limitRows"), PH_NOISY_CC); PHALCON_OBS_VAR(config); phalcon_read_property(&config, this_ptr, SL("_config"), PH_NOISY_CC); PHALCON_OBS_VAR(items); phalcon_array_fetch_string(&items, config, SL("data"), PH_NOISY_CC); PHALCON_OBS_VAR(page_number); phalcon_read_property(&page_number, this_ptr, SL("_page"), PH_NOISY_CC); if (Z_TYPE_P(page_number) == IS_NULL) { PHALCON_CPY_WRT(page_number, one); } PHALCON_INIT_VAR(smaller); is_smaller_function(smaller, show, zero TSRMLS_CC); if (PHALCON_IS_TRUE(smaller)) { PHALCON_THROW_EXCEPTION_STR(phalcon_paginator_exception_ce, "The start page number is zero or less"); return; } PHALCON_INIT_VAR(n); phalcon_fast_count(n, items TSRMLS_CC); PHALCON_INIT_VAR(page); object_init(page); PHALCON_INIT_VAR(last_show_page); sub_function(last_show_page, page_number, one TSRMLS_CC); PHALCON_INIT_VAR(start); mul_function(start, show, last_show_page TSRMLS_CC); PHALCON_INIT_VAR(last_page); sub_function(last_page, n, one TSRMLS_CC); PHALCON_INIT_VAR(possible_pages); div_function(possible_pages, last_page, show TSRMLS_CC); PHALCON_INIT_VAR(total_pages); PHALCON_CALL_FUNC_PARAMS_1(total_pages, "ceil", possible_pages); if (Z_TYPE_P(items) != IS_OBJECT) { PHALCON_THROW_EXCEPTION_STR(phalcon_paginator_exception_ce, "Invalid data for paginator"); return; } if (Z_TYPE_P(page_number) == IS_NULL) { PHALCON_CPY_WRT(page_number, zero); } PHALCON_INIT_VAR(compare); is_smaller_function(compare, start, zero TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_THROW_EXCEPTION_STR(phalcon_paginator_exception_ce, "The start page number is zero or less"); return; } PHALCON_INIT_VAR(page_items); array_init(page_items); is_smaller_function(compare, zero, n TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { /** * Seek to the desired position */ is_smaller_or_equal_function(compare, start, n TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(items, "seek", start); } else { PHALCON_CALL_METHOD_PARAMS_1_NORETURN(items, "seek", one); PHALCON_CPY_WRT(page_number, one); } /** * The record must be iterable */ PHALCON_INIT_VAR(i); ZVAL_LONG(i, 1); while (1) { PHALCON_INIT_NVAR(r0); PHALCON_CALL_METHOD(r0, items, "valid"); PHALCON_CPY_WRT(valid, r0); if (PHALCON_IS_NOT_FALSE(valid)) { } else { break; } PHALCON_INIT_NVAR(current); PHALCON_CALL_METHOD(current, items, "current"); phalcon_array_append(&page_items, current, PH_SEPARATE TSRMLS_CC); PHALCON_INIT_NVAR(compare); is_smaller_or_equal_function(compare, show, i TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { break; } PHALCON_SEPARATE(i); increment_function(i); } } phalcon_update_property_zval(page, SL("items"), page_items TSRMLS_CC); phalcon_update_property_zval(page, SL("first"), one TSRMLS_CC); PHALCON_INIT_VAR(maximum_pages); phalcon_add_function(maximum_pages, start, show TSRMLS_CC); is_smaller_function(compare, maximum_pages, n TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_INIT_VAR(next); phalcon_add_function(next, page_number, one TSRMLS_CC); } else { is_equal_function(compare, maximum_pages, n TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_CPY_WRT(next, n); } else { div_function(possible_pages, n, show TSRMLS_CC); PHALCON_INIT_VAR(additional_page); phalcon_add_function(additional_page, possible_pages, one TSRMLS_CC); PHALCON_INIT_NVAR(next); PHALCON_CALL_FUNC_PARAMS_1(next, "intval", additional_page); } } is_smaller_function(compare, total_pages, next TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_CPY_WRT(next, total_pages); } phalcon_update_property_zval(page, SL("next"), next TSRMLS_CC); is_smaller_function(compare, one, page_number TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_INIT_VAR(before); sub_function(before, page_number, one TSRMLS_CC); } else { PHALCON_CPY_WRT(before, one); } phalcon_update_property_zval(page, SL("before"), before TSRMLS_CC); phalcon_update_property_zval(page, SL("current"), page_number TSRMLS_CC); PHALCON_INIT_VAR(remainder); mod_function(remainder, n, show TSRMLS_CC); div_function(possible_pages, n, show TSRMLS_CC); if (!PHALCON_IS_LONG(remainder, 0)) { PHALCON_INIT_NVAR(next); phalcon_add_function(next, possible_pages, one TSRMLS_CC); PHALCON_INIT_VAR(pages_total); PHALCON_CALL_FUNC_PARAMS_1(pages_total, "intval", next); } else { PHALCON_CPY_WRT(pages_total, possible_pages); } phalcon_update_property_zval(page, SL("last"), pages_total TSRMLS_CC); phalcon_update_property_zval(page, SL("total_pages"), pages_total TSRMLS_CC); RETURN_CTOR(page); }
tmihalik/cphalcon
ext/http/responseinterface.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "kernel/main.h" /** * Phalcon\Http\ResponseInterface initializer */ PHALCON_INIT_CLASS(Phalcon_Http_ResponseInterface){ PHALCON_REGISTER_INTERFACE(Phalcon\\Http, ResponseInterface, http_responseinterface, phalcon_http_responseinterface_method_entry); return SUCCESS; } /** * Sets the HTTP response code * * @param int $code * @param string $message * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setStatusCode); /** * Returns headers set by the user * * @return Phalcon\Http\Response\Headers */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, getHeaders); /** * Overwrites a header in the response * * @param string $name * @param string $value * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setHeader); /** * Send a raw header to the response * * @param string $header * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setRawHeader); /** * Resets all the stablished headers * * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, resetHeaders); /** * Sets output expire time header * * @param DateTime $datetime * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setExpires); /** * Sends a Not-Modified response * * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setNotModified); /** * Sets the response content-type mime, optionally the charset * * @param string $contentType * @param string $charset * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setContentType); /** * Redirect by HTTP to another action or URL * * @param string $location * @param boolean $externalRedirect * @param int $statusCode * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, redirect); /** * Sets HTTP response body * * @param string $content * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, setContent); /** * Appends a string to the HTTP response body * * @param string $content * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, appendContent); /** * Gets the HTTP response body * * @return string */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, getContent); /** * Sends headers to the client * * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, sendHeaders); /** * Prints out HTTP response to the client * * @return Phalcon\Http\ResponseInterface */ PHALCON_DOC_METHOD(Phalcon_Http_ResponseInterface, send);
tmihalik/cphalcon
ext/mvc/view/engine/volt/compiler.h
<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_view_engine_volt_compiler_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine_Volt_Compiler); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, __construct); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, setOptions); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getOptions); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, setDI); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getDI); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, addFunction); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getFunctions); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, addFilter); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getFilters); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, attributeReader); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, functionCall); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveTest); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveFilter); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, expression); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementListOrExtends); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileForeach); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileIf); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileElseIf); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileCache); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileEcho); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileInclude); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileSet); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileDo); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileAutoEscape); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementList); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, _compileSource); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileString); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compileFile); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, compile); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, getCompiledTemplatePath); PHP_METHOD(Phalcon_Mvc_View_Engine_Volt_Compiler, parse); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler___construct, 0, 0, 0) ZEND_ARG_INFO(0, view) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_setoptions, 0, 0, 1) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_setdi, 0, 0, 1) ZEND_ARG_INFO(0, dependencyInjector) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_addfunction, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, definition) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_addfilter, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, definition) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_attributereader, 0, 0, 1) ZEND_ARG_INFO(0, expr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_functioncall, 0, 0, 1) ZEND_ARG_INFO(0, expr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_resolvetest, 0, 0, 2) ZEND_ARG_INFO(0, test) ZEND_ARG_INFO(0, left) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_expression, 0, 0, 1) ZEND_ARG_INFO(0, expr) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileforeach, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileif, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileelseif, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compilecache, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileecho, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileinclude, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileset, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compiledo, 0, 0, 1) ZEND_ARG_INFO(0, statement) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compileautoescape, 0, 0, 2) ZEND_ARG_INFO(0, statement) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compilestring, 0, 0, 1) ZEND_ARG_INFO(0, viewCode) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compilefile, 0, 0, 2) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, compiledPath) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_compile, 0, 0, 1) ZEND_ARG_INFO(0, templatePath) ZEND_ARG_INFO(0, extendsMode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine_volt_compiler_parse, 0, 0, 1) ZEND_ARG_INFO(0, viewCode) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_view_engine_volt_compiler_method_entry){ PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, __construct, arginfo_phalcon_mvc_view_engine_volt_compiler___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, setOptions, arginfo_phalcon_mvc_view_engine_volt_compiler_setoptions, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, getOptions, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, setDI, arginfo_phalcon_mvc_view_engine_volt_compiler_setdi, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, getDI, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, addFunction, arginfo_phalcon_mvc_view_engine_volt_compiler_addfunction, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, getFunctions, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, addFilter, arginfo_phalcon_mvc_view_engine_volt_compiler_addfilter, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, getFilters, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, attributeReader, arginfo_phalcon_mvc_view_engine_volt_compiler_attributereader, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, functionCall, arginfo_phalcon_mvc_view_engine_volt_compiler_functioncall, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveTest, arginfo_phalcon_mvc_view_engine_volt_compiler_resolvetest, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, resolveFilter, NULL, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, expression, arginfo_phalcon_mvc_view_engine_volt_compiler_expression, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementListOrExtends, NULL, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileForeach, arginfo_phalcon_mvc_view_engine_volt_compiler_compileforeach, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileIf, arginfo_phalcon_mvc_view_engine_volt_compiler_compileif, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileElseIf, arginfo_phalcon_mvc_view_engine_volt_compiler_compileelseif, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileCache, arginfo_phalcon_mvc_view_engine_volt_compiler_compilecache, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileEcho, arginfo_phalcon_mvc_view_engine_volt_compiler_compileecho, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileInclude, arginfo_phalcon_mvc_view_engine_volt_compiler_compileinclude, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileSet, arginfo_phalcon_mvc_view_engine_volt_compiler_compileset, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileDo, arginfo_phalcon_mvc_view_engine_volt_compiler_compiledo, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileAutoEscape, arginfo_phalcon_mvc_view_engine_volt_compiler_compileautoescape, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, _statementList, NULL, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, _compileSource, NULL, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileString, arginfo_phalcon_mvc_view_engine_volt_compiler_compilestring, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compileFile, arginfo_phalcon_mvc_view_engine_volt_compiler_compilefile, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, compile, arginfo_phalcon_mvc_view_engine_volt_compiler_compile, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, getCompiledTemplatePath, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine_Volt_Compiler, parse, arginfo_phalcon_mvc_view_engine_volt_compiler_parse, ZEND_ACC_PUBLIC) PHP_FE_END };
tmihalik/cphalcon
ext/mvc/model/resultset/simple.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/fcall.h" #include "kernel/operators.h" #include "kernel/array.h" #include "kernel/exception.h" /** * Phalcon\Mvc\Model\Resultset\Simple * * Simple resultsets only contains a complete objects * This class builds every complete object as it is required */ /** * Phalcon\Mvc\Model\Resultset\Simple initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Resultset_Simple){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\Model\\Resultset, Simple, mvc_model_resultset_simple, "phalcon\\mvc\\model\\resultset", phalcon_mvc_model_resultset_simple_method_entry, 0); zend_declare_property_null(phalcon_mvc_model_resultset_simple_ce, SL("_model"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_mvc_model_resultset_simple_ce, SL("_columnMap"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_model_resultset_simple_ce TSRMLS_CC, 5, zend_ce_iterator, spl_ce_SeekableIterator, spl_ce_Countable, zend_ce_arrayaccess, zend_ce_serializable); return SUCCESS; } /** * Phalcon\Mvc\Model\Resultset\Simple constructor * * @param array $columnMap * @param Phalcon\Mvc\ModelInterface $model * @param Phalcon\Db\Result\Pdo $result * @param Phalcon\Cache\BackendInterface $cache */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, __construct){ zval *column_map, *model, *result, *cache = NULL, *fetch_assoc; zval *limit, *row_count, *big_resultset; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz|z", &column_map, &model, &result, &cache) == FAILURE) { RETURN_MM_NULL(); } if (!cache) { PHALCON_INIT_VAR(cache); } phalcon_update_property_zval(this_ptr, SL("_model"), model TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_result"), result TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_cache"), cache TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_columnMap"), column_map TSRMLS_CC); if (Z_TYPE_P(result) == IS_OBJECT) { PHALCON_INIT_VAR(fetch_assoc); ZVAL_LONG(fetch_assoc, 1); PHALCON_CALL_METHOD_PARAMS_1_NORETURN(result, "setfetchmode", fetch_assoc); PHALCON_INIT_VAR(limit); ZVAL_LONG(limit, 32); PHALCON_INIT_VAR(row_count); PHALCON_CALL_METHOD(row_count, result, "numrows"); /** * Check if it's a big resultset */ PHALCON_INIT_VAR(big_resultset); is_smaller_function(big_resultset, limit, row_count TSRMLS_CC); if (PHALCON_IS_TRUE(big_resultset)) { phalcon_update_property_long(this_ptr, SL("_type"), 1 TSRMLS_CC); } else { phalcon_update_property_long(this_ptr, SL("_type"), 0 TSRMLS_CC); } /** * Update the row-count */ phalcon_update_property_zval(this_ptr, SL("_count"), row_count TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Check whether internal resource has rows to fetch * * @return boolean */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, valid){ zval *type, *result = NULL, *row = NULL, *rows = NULL, *hydrate_mode, *column_map; zval *model, *active_row = NULL; PHALCON_MM_GROW(); PHALCON_OBS_VAR(type); phalcon_read_property(&type, this_ptr, SL("_type"), PH_NOISY_CC); if (zend_is_true(type)) { PHALCON_OBS_VAR(result); phalcon_read_property(&result, this_ptr, SL("_result"), PH_NOISY_CC); if (Z_TYPE_P(result) == IS_OBJECT) { PHALCON_INIT_VAR(row); PHALCON_CALL_METHOD_PARAMS_1(row, result, "fetch", result); } else { PHALCON_INIT_NVAR(row); ZVAL_BOOL(row, 0); } } else { PHALCON_OBS_VAR(rows); phalcon_read_property(&rows, this_ptr, SL("_rows"), PH_NOISY_CC); if (Z_TYPE_P(rows) != IS_ARRAY) { PHALCON_OBS_NVAR(result); phalcon_read_property(&result, this_ptr, SL("_result"), PH_NOISY_CC); if (Z_TYPE_P(result) == IS_OBJECT) { PHALCON_INIT_NVAR(rows); PHALCON_CALL_METHOD(rows, result, "fetchall"); phalcon_update_property_zval(this_ptr, SL("_rows"), rows TSRMLS_CC); } } if (Z_TYPE_P(rows) == IS_ARRAY) { PHALCON_INIT_NVAR(row); phalcon_array_get_current(row, rows TSRMLS_CC); if (PHALCON_IS_NOT_FALSE(row)) { phalcon_array_next(rows); } } else { PHALCON_INIT_NVAR(row); ZVAL_BOOL(row, 0); } } if (Z_TYPE_P(row) != IS_ARRAY) { phalcon_update_property_bool(this_ptr, SL("_activeRow"), 0 TSRMLS_CC); RETURN_MM_FALSE; } /** * Get current hydration mode */ PHALCON_OBS_VAR(hydrate_mode); phalcon_read_property(&hydrate_mode, this_ptr, SL("_hydrateMode"), PH_NOISY_CC); PHALCON_OBS_VAR(column_map); phalcon_read_property(&column_map, this_ptr, SL("_columnMap"), PH_NOISY_CC); switch (phalcon_get_intval(hydrate_mode)) { case 0: PHALCON_OBS_VAR(model); phalcon_read_property(&model, this_ptr, SL("_model"), PH_NOISY_CC); /** * Performs the standard hydration based on objects */ PHALCON_INIT_VAR(active_row); PHALCON_CALL_STATIC_PARAMS_3(active_row, "phalcon\\mvc\\model", "cloneresultmap", model, row, column_map); break; default: /** * Other kinds of hydrations */ PHALCON_INIT_NVAR(active_row); PHALCON_CALL_STATIC_PARAMS_3(active_row, "phalcon\\mvc\\model", "cloneresultmaphydrate", row, column_map, hydrate_mode); break; } phalcon_update_property_zval(this_ptr, SL("_activeRow"), active_row TSRMLS_CC); RETURN_MM_TRUE; } /** * Returns a complete resultset as an array, if the resultset has a big number of rows * it could consume more memory than currently it does. * * @return array */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, toArray){ zval *type, *result = NULL, *active_row = NULL, *records = NULL, *row_count; PHALCON_MM_GROW(); PHALCON_OBS_VAR(type); phalcon_read_property(&type, this_ptr, SL("_type"), PH_NOISY_CC); if (zend_is_true(type)) { PHALCON_OBS_VAR(result); phalcon_read_property(&result, this_ptr, SL("_result"), PH_NOISY_CC); if (Z_TYPE_P(result) == IS_OBJECT) { PHALCON_OBS_VAR(active_row); phalcon_read_property(&active_row, this_ptr, SL("_activeRow"), PH_NOISY_CC); /** * Check if we need to re-execute the query */ if (Z_TYPE_P(active_row) != IS_NULL) { PHALCON_CALL_METHOD_NORETURN(result, "execute"); } /** * We fetch all the results in memory */ PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD(records, result, "fetchall"); } else { PHALCON_INIT_NVAR(records); array_init(records); } } else { PHALCON_OBS_NVAR(records); phalcon_read_property(&records, this_ptr, SL("_rows"), PH_NOISY_CC); if (Z_TYPE_P(records) != IS_ARRAY) { PHALCON_OBS_NVAR(result); phalcon_read_property(&result, this_ptr, SL("_result"), PH_NOISY_CC); if (Z_TYPE_P(result) == IS_OBJECT) { PHALCON_OBS_NVAR(active_row); phalcon_read_property(&active_row, this_ptr, SL("_activeRow"), PH_NOISY_CC); /** * Check if we need to re-execute the query */ if (Z_TYPE_P(active_row) != IS_NULL) { PHALCON_CALL_METHOD_NORETURN(result, "execute"); } /** * We fetch all the results in memory again */ PHALCON_INIT_NVAR(records); PHALCON_CALL_METHOD(records, result, "fetchall"); phalcon_update_property_zval(this_ptr, SL("_rows"), records TSRMLS_CC); /** * Update the row count */ PHALCON_INIT_VAR(row_count); phalcon_fast_count(row_count, records TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_count"), row_count TSRMLS_CC); } } } RETURN_CCTOR(records); } /** * Serializing a resultset will dump all related rows into a big array * * @return string */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, serialize){ zval *records, *model, *cache, *column_map, *hydrate_mode; zval *data, *serialized; PHALCON_MM_GROW(); PHALCON_INIT_VAR(records); PHALCON_CALL_METHOD(records, this_ptr, "toarray"); PHALCON_OBS_VAR(model); phalcon_read_property(&model, this_ptr, SL("_model"), PH_NOISY_CC); PHALCON_OBS_VAR(cache); phalcon_read_property(&cache, this_ptr, SL("_cache"), PH_NOISY_CC); PHALCON_OBS_VAR(column_map); phalcon_read_property(&column_map, this_ptr, SL("_columnMap"), PH_NOISY_CC); PHALCON_OBS_VAR(hydrate_mode); phalcon_read_property(&hydrate_mode, this_ptr, SL("_hydrateMode"), PH_NOISY_CC); PHALCON_INIT_VAR(data); array_init_size(data, 5); phalcon_array_update_string(&data, SL("model"), &model, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("cache"), &cache, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("rows"), &records, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("columnMap"), &column_map, PH_COPY | PH_SEPARATE TSRMLS_CC); phalcon_array_update_string(&data, SL("hydrateMode"), &hydrate_mode, PH_COPY | PH_SEPARATE TSRMLS_CC); /** * Force to re-execute the query */ phalcon_update_property_bool(this_ptr, SL("_activeRow"), 0 TSRMLS_CC); /** * Serialize the cache using the serialize function */ PHALCON_INIT_VAR(serialized); PHALCON_CALL_FUNC_PARAMS_1(serialized, "serialize", data); RETURN_CCTOR(serialized); } /** * Unserializing a resultset will allow to only works on the rows present in the saved state * * @param string $data */ PHP_METHOD(Phalcon_Mvc_Model_Resultset_Simple, unserialize){ zval *data, *resultset, *model, *rows, *cache, *column_map; zval *hydrate_mode; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } phalcon_update_property_long(this_ptr, SL("_type"), 0 TSRMLS_CC); PHALCON_INIT_VAR(resultset); PHALCON_CALL_FUNC_PARAMS_1(resultset, "unserialize", data); if (Z_TYPE_P(resultset) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_model_exception_ce, "Invalid serialization data"); return; } PHALCON_OBS_VAR(model); phalcon_array_fetch_string(&model, resultset, SL("model"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_model"), model TSRMLS_CC); PHALCON_OBS_VAR(rows); phalcon_array_fetch_string(&rows, resultset, SL("rows"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_rows"), rows TSRMLS_CC); PHALCON_OBS_VAR(cache); phalcon_array_fetch_string(&cache, resultset, SL("cache"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_cache"), cache TSRMLS_CC); PHALCON_OBS_VAR(column_map); phalcon_array_fetch_string(&column_map, resultset, SL("columnMap"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_columnMap"), column_map TSRMLS_CC); PHALCON_OBS_VAR(hydrate_mode); phalcon_array_fetch_string(&hydrate_mode, resultset, SL("hydrateMode"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_hydrateMode"), hydrate_mode TSRMLS_CC); PHALCON_MM_RESTORE(); }
tmihalik/cphalcon
ext/mvc/model/query/parser.h
#define PHQL_BETWEEN 1 #define PHQL_EQUALS 2 #define PHQL_NOTEQUALS 3 #define PHQL_LESS 4 #define PHQL_GREATER 5 #define PHQL_GREATEREQUAL 6 #define PHQL_LESSEQUAL 7 #define PHQL_AND 8 #define PHQL_OR 9 #define PHQL_LIKE 10 #define PHQL_BITWISE_AND 11 #define PHQL_BITWISE_OR 12 #define PHQL_DIVIDE 13 #define PHQL_TIMES 14 #define PHQL_MOD 15 #define PHQL_PLUS 16 #define PHQL_MINUS 17 #define PHQL_IS 18 #define PHQL_IN 19 #define PHQL_DISTINCT 20 #define PHQL_NOT 21 #define PHQL_SELECT 22 #define PHQL_FROM 23 #define PHQL_COMMA 24 #define PHQL_IDENTIFIER 25 #define PHQL_DOT 26 #define PHQL_AS 27 #define PHQL_JOIN 28 #define PHQL_INNER 29 #define PHQL_CROSS 30 #define PHQL_LEFT 31 #define PHQL_OUTER 32 #define PHQL_RIGHT 33 #define PHQL_FULL 34 #define PHQL_ON 35 #define PHQL_INSERT 36 #define PHQL_INTO 37 #define PHQL_VALUES 38 #define PHQL_BRACKET_OPEN 39 #define PHQL_BRACKET_CLOSE 40 #define PHQL_UPDATE 41 #define PHQL_SET 42 #define PHQL_DELETE 43 #define PHQL_WHERE 44 #define PHQL_ORDER 45 #define PHQL_BY 46 #define PHQL_ASC 47 #define PHQL_DESC 48 #define PHQL_INTEGER 49 #define PHQL_GROUP 50 #define PHQL_HAVING 51 #define PHQL_LIMIT 52 #define PHQL_OFFSET 53 #define PHQL_NULL 54 #define PHQL_STRING 55 #define PHQL_DOUBLE 56 #define PHQL_NPLACEHOLDER 57 #define PHQL_SPLACEHOLDER 58
tmihalik/cphalcon
ext/kernel/object.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #ifdef PHP_WIN32 #include "php_string.h" #endif #include "php_phalcon.h" #include "phalcon.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/exception.h" #include "kernel/fcall.h" #include "kernel/array.h" /** * Reads class constant from string name and returns its value */ int phalcon_get_class_constant(zval *return_value, zend_class_entry *ce, char *constant_name, unsigned int constant_length TSRMLS_DC) { zval **result_ptr; if (zend_hash_find(&ce->constants_table, constant_name, constant_length, (void **) &result_ptr) != SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Undefined class constant '%s::%s'", ce->name, constant_name); phalcon_memory_restore_stack(TSRMLS_C); return FAILURE; } ZVAL_ZVAL(return_value, *result_ptr, 1, 0); return SUCCESS; } /** * Check if class is instance of */ int phalcon_instance_of(zval *result, const zval *object, const zend_class_entry *ce TSRMLS_DC) { if (Z_TYPE_P(object) != IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "instanceof expects an object instance, constant given"); phalcon_memory_restore_stack(TSRMLS_C); return FAILURE; } ZVAL_BOOL(result, instanceof_function(Z_OBJCE_P(object), ce TSRMLS_CC)); return SUCCESS; } /** * Check if an object is instance of a class */ int phalcon_is_instance_of(zval *object, char *class_name, unsigned int class_length TSRMLS_DC) { zend_class_entry *ce; if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); if (ce->name_length == class_length) { return !zend_binary_strcasecmp(ce->name, ce->name_length, class_name, class_length); } } return 0; } /** * Returns a class name into a zval result */ void phalcon_get_class(zval *result, zval *object, int lower TSRMLS_DC) { zend_class_entry *ce; if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); Z_STRLEN_P(result) = ce->name_length; Z_STRVAL_P(result) = (char *) emalloc(ce->name_length + 1); memcpy(Z_STRVAL_P(result), ce->name, ce->name_length); Z_STRVAL_P(result)[Z_STRLEN_P(result)] = 0; Z_TYPE_P(result) = IS_STRING; if (lower) { zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result)); } } else { ZVAL_NULL(result); php_error_docref(NULL TSRMLS_CC, E_WARNING, "phalcon_get_class expects an object"); } } /** * Returns a class name into a zval result */ void phalcon_get_class_ns(zval *result, zval *object, int lower TSRMLS_DC) { int found = 0; zend_class_entry *ce; unsigned int i, class_length; const char *cursor, *class_name; if (Z_TYPE_P(object) != IS_OBJECT) { if (Z_TYPE_P(object) != IS_STRING) { ZVAL_NULL(result); php_error_docref(NULL TSRMLS_CC, E_WARNING, "phalcon_get_class_ns expects an object"); return; } } if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); class_name = ce->name; class_length = ce->name_length; } else { class_name = Z_STRVAL_P(object); class_length = Z_STRLEN_P(object); } if (!class_length) { ZVAL_NULL(result); return; } i = class_length; cursor = (char *) (class_name + class_length - 1); while (i > 0) { if ((*cursor) == '\\') { found = 1; break; } cursor--; i--; } if (found) { Z_STRLEN_P(result) = class_length - i; Z_STRVAL_P(result) = (char *) emalloc(class_length - i + 1); memcpy(Z_STRVAL_P(result), class_name + i, class_length - i); Z_STRVAL_P(result)[Z_STRLEN_P(result)] = 0; Z_TYPE_P(result) = IS_STRING; } else { ZVAL_STRINGL(result, class_name, class_length, 1); } if (lower) { zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result)); } } /** * Returns a namespace from a class name */ void phalcon_get_ns_class(zval *result, zval *object, int lower TSRMLS_DC) { zend_class_entry *ce; int found = 0; unsigned int i, j, class_length; const char *cursor, *class_name; if (Z_TYPE_P(object) != IS_OBJECT) { if (Z_TYPE_P(object) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "phalcon_get_ns_class expects an object"); ZVAL_NULL(result); return; } } if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); class_name = ce->name; class_length = ce->name_length; } else { class_name = Z_STRVAL_P(object); class_length = Z_STRLEN_P(object); } if (!class_length) { ZVAL_NULL(result); return; } j = 0; i = class_length; cursor = (char *) (class_name + class_length - 1); while (i > 0) { if ((*cursor) == '\\') { found = 1; break; } cursor--; i--; j++; } if (j > 0) { if (found) { Z_STRLEN_P(result) = class_length - j - 1; Z_STRVAL_P(result) = (char *) emalloc(class_length - j); memcpy(Z_STRVAL_P(result), class_name, class_length - j - 1); Z_STRVAL_P(result)[Z_STRLEN_P(result)] = 0; Z_TYPE_P(result) = IS_STRING; } else { ZVAL_EMPTY_STRING(result); } if (lower) { zend_str_tolower(Z_STRVAL_P(result), Z_STRLEN_P(result)); } } else { ZVAL_NULL(result); } } /** * Returns the called in class in the current scope */ void phalcon_get_called_class(zval *return_value TSRMLS_DC) { if (EG(called_scope)) { RETURN_STRINGL(EG(called_scope)->name, EG(called_scope)->name_length, 1); } if (!EG(scope)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "phalcon_get_called_class() called from outside a class"); } } /** * Fetches a zend class entry from a zval value */ zend_class_entry *phalcon_fetch_class(zval *class_name TSRMLS_DC) { if (Z_TYPE_P(class_name) == IS_STRING) { return zend_fetch_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); } php_error_docref(NULL TSRMLS_CC, E_WARNING, "class name must be a string"); return zend_fetch_class("stdclass", strlen("stdclass"), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); } /** * Checks if a class exist */ int phalcon_class_exists(zval *class_name TSRMLS_DC) { zend_class_entry **ce; if (Z_TYPE_P(class_name) == IS_STRING) { if (zend_lookup_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), &ce TSRMLS_CC) == SUCCESS) { return (((*ce)->ce_flags & ZEND_ACC_INTERFACE) == 0); } return 0; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "class name must be a string"); return 0; } /** * Clones an object from obj to destiny */ int phalcon_clone(zval *destiny, zval *obj TSRMLS_DC) { int status = SUCCESS; zend_class_entry *ce; zend_object_clone_obj_t clone_call; if (Z_TYPE_P(obj) != IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "__clone method called on non-object"); status = FAILURE; } else { ce = Z_OBJCE_P(obj); clone_call = Z_OBJ_HT_P(obj)->clone_obj; if (!clone_call) { if (ce) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Trying to clone an uncloneable object of class %s", ce->name); } else { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Trying to clone an uncloneable object"); } status = FAILURE; } else { if (!EG(exception)) { Z_OBJVAL_P(destiny) = clone_call(obj TSRMLS_CC); Z_TYPE_P(destiny) = IS_OBJECT; Z_SET_REFCOUNT_P(destiny, 1); Z_UNSET_ISREF_P(destiny); if (EG(exception)) { zval_ptr_dtor(&destiny); } } } } if (status == FAILURE){ phalcon_memory_restore_stack(TSRMLS_C); } return status; } /** * Checks if property exists on object */ int phalcon_isset_property(zval *object, char *property_name, unsigned int property_length TSRMLS_DC) { unsigned long hash; hash = zend_inline_hash_func(property_name, property_length); if (Z_TYPE_P(object) == IS_OBJECT) { if (zend_hash_quick_exists(&Z_OBJCE_P(object)->properties_info, property_name, property_length, hash)) { return 1; } else { return zend_hash_quick_exists(Z_OBJ_HT_P(object)->get_properties(object TSRMLS_CC), property_name, property_length, hash); } } return 0; } /** * Checks if string property exists on object */ int phalcon_isset_property_zval(zval *object, zval *property TSRMLS_DC) { unsigned long hash; if (Z_TYPE_P(object) == IS_OBJECT) { if (Z_TYPE_P(property) == IS_STRING) { hash = zend_inline_hash_func(Z_STRVAL_P(property), Z_STRLEN_P(property)+1); if (zend_hash_quick_exists(&Z_OBJCE_P(object)->properties_info, Z_STRVAL_P(property), Z_STRLEN_P(property)+1, hash)) { return 1; } else { return zend_hash_quick_exists(Z_OBJ_HT_P(object)->get_properties(object TSRMLS_CC), Z_STRVAL_P(property), Z_STRLEN_P(property)+1, hash); } } } return 0; } /** * Lookup exact class where a property is defined * */ static inline zend_class_entry *phalcon_lookup_class_ce(zend_class_entry *ce, char *property_name, unsigned int property_length TSRMLS_DC) { zend_class_entry *original_ce; unsigned long hash; hash = zend_inline_hash_func(property_name, property_length+1); original_ce = ce; while (ce) { if (zend_hash_quick_exists(&ce->properties_info, property_name, property_length+1, hash)) { return ce; } ce = ce->parent; } return original_ce; } /** * Reads a property from an object */ int phalcon_read_property(zval **result, zval *object, char *property_name, unsigned int property_length, int silent TSRMLS_DC) { zval *property; zend_class_entry *ce, *old_scope; if (likely(Z_TYPE_P(object) == IS_OBJECT)) { ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->read_property) { ALLOC_INIT_ZVAL(*result); ZVAL_NULL(*result); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be read", property_name, ce->name); return FAILURE; } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, property_name, property_length, 0); #if PHP_VERSION_ID < 50400 *result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R TSRMLS_CC); #else *result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R, 0 TSRMLS_CC); #endif Z_ADDREF_PP(result); ZVAL_NULL(property); zval_ptr_dtor(&property); EG(scope) = old_scope; return SUCCESS; } else { if (silent == PH_NOISY) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Trying to get property of non-object"); } } ALLOC_INIT_ZVAL(*result); ZVAL_NULL(*result); return FAILURE; } /** * Returns an object's member */ int phalcon_return_property(zval *return_value, zval *object, char *property_name, unsigned int property_length TSRMLS_DC) { zval *property, *result; zend_class_entry *ce, *old_scope; if (likely(Z_TYPE_P(object) == IS_OBJECT)) { ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->read_property) { ZVAL_NULL(return_value); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be read", property_name, ce->name); return FAILURE; } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, property_name, property_length, 0); #if PHP_VERSION_ID < 50400 result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R TSRMLS_CC); #else result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R, 0 TSRMLS_CC); #endif ZVAL_NULL(property); zval_ptr_dtor(&property); EG(scope) = old_scope; ZVAL_ZVAL(return_value, result, 1, 0); return SUCCESS; } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Trying to get property of non-object"); } return FAILURE; } /** * Reads a property from an object */ int phalcon_read_property_zval(zval **result, zval *object, zval *property, int silent TSRMLS_DC) { zend_class_entry *ce, *old_scope; if (Z_TYPE_P(object) == IS_OBJECT) { if (Z_TYPE_P(property) == IS_STRING) { ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, Z_STRVAL_P(property), Z_STRLEN_P(property) TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->read_property) { ALLOC_INIT_ZVAL(*result); ZVAL_NULL(*result); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be read", Z_STRVAL_P(property), ce->name); return FAILURE; } #if PHP_VERSION_ID < 50400 *result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R TSRMLS_CC); #else *result = Z_OBJ_HT_P(object)->read_property(object, property, BP_VAR_R, 0 TSRMLS_CC); #endif Z_ADDREF_PP(result); EG(scope) = old_scope; return SUCCESS; } else { if (silent == PH_NOISY) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot access empty property %d", Z_TYPE_P(property)); } } } else { if (silent == PH_NOISY) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Trying to get property of non-object"); } } ALLOC_INIT_ZVAL(*result); ZVAL_NULL(*result); return FAILURE; } /** * Checks whether obj is an object and updates property with long value */ int phalcon_update_property_long(zval *object, char *property_name, unsigned int property_length, long value TSRMLS_DC) { zend_class_entry *ce; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } zend_update_property_long(ce, object, property_name, property_length, value TSRMLS_CC); return SUCCESS; } /** * Checks whether obj is an object and updates property with string value */ int phalcon_update_property_string(zval *object, char *property_name, unsigned int property_length, char *str, unsigned int str_length TSRMLS_DC) { zval *value, *property; zend_class_entry *ce, *old_scope; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->write_property) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be updated", property_name, ce->name); return FAILURE; } MAKE_STD_ZVAL(value); ZVAL_STRINGL(value, str, str_length, 1); MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, property_name, property_length, 0); #if PHP_VERSION_ID < 50400 Z_OBJ_HT_P(object)->write_property(object, property, value TSRMLS_CC); #else Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); #endif ZVAL_NULL(property); zval_ptr_dtor(&property); EG(scope) = old_scope; return SUCCESS; } /** * Checks whether obj is an object and updates property with bool value */ int phalcon_update_property_bool(zval *object, char *property_name, unsigned int property_length, int value TSRMLS_DC) { zend_class_entry *ce; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } zend_update_property_bool(ce, object, property_name, property_length, value TSRMLS_CC); return SUCCESS; } /** * Checks whether obj is an object and updates property with null value */ int phalcon_update_property_null(zval *object, char *property_name, unsigned int property_length TSRMLS_DC) { zend_class_entry *ce; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } zend_update_property_null(ce, object, property_name, property_length TSRMLS_CC); return SUCCESS; } /** * Checks whether obj is an object and updates property with another zval */ int phalcon_update_property_zval(zval *object, char *property_name, unsigned int property_length, zval *value TSRMLS_DC){ zend_class_entry *ce, *old_scope; zval *property; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->write_property) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be updated", property_name, ce->name); return FAILURE; } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, property_name, property_length, 0); #if PHP_VERSION_ID < 50400 Z_OBJ_HT_P(object)->write_property(object, property, value TSRMLS_CC); #else Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); #endif ZVAL_NULL(property); zval_ptr_dtor(&property); EG(scope) = old_scope; return SUCCESS; } /** * Checks whether obj is an object and updates zval property with another zval */ int phalcon_update_property_zval_zval(zval *object, zval *property, zval *value TSRMLS_DC){ zend_class_entry *ce, *old_scope; if (unlikely(Z_TYPE_P(object) != IS_OBJECT)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } if (Z_TYPE_P(property) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property should be string"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, Z_STRVAL_P(property), Z_STRLEN_P(property) TSRMLS_CC); } old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->write_property) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be updated", Z_STRVAL_P(property), ce->name); return FAILURE; } #if PHP_VERSION_ID < 50400 Z_OBJ_HT_P(object)->write_property(object, property, value TSRMLS_CC); #else Z_OBJ_HT_P(object)->write_property(object, property, value, 0 TSRMLS_CC); #endif EG(scope) = old_scope; return SUCCESS; } /** * Updates an array property */ int phalcon_update_property_array(zval *object, char *property, unsigned int property_length, zval *index, zval *value TSRMLS_DC) { zval *tmp; int separated = 0; if (Z_TYPE_P(object) == IS_OBJECT) { phalcon_read_property(&tmp, object, property, property_length, PH_NOISY_CC); /** Separation only when refcount > 2 */ if (Z_REFCOUNT_P(tmp) > 2) { zval *new_zv; Z_DELREF_P(tmp); ALLOC_ZVAL(new_zv); INIT_PZVAL_COPY(new_zv, tmp); tmp = new_zv; zval_copy_ctor(new_zv); separated = 1; } /** Convert the value to array if not is an array */ if (Z_TYPE_P(tmp) != IS_ARRAY) { if (separated) { convert_to_array(tmp); } else { zval_ptr_dtor(&tmp); ALLOC_INIT_ZVAL(tmp); array_init(tmp); separated = 1; } } Z_ADDREF_P(value); if (Z_TYPE_P(index) == IS_STRING) { zend_hash_update(Z_ARRVAL_P(tmp), Z_STRVAL_P(index), Z_STRLEN_P(index)+1, &value, sizeof(zval *), NULL); } else { if (Z_TYPE_P(index) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(tmp), Z_LVAL_P(index), &value, sizeof(zval *), NULL); } } if (separated) { phalcon_update_property_zval(object, property, property_length, tmp TSRMLS_CC); } zval_ptr_dtor(&tmp); } return SUCCESS; } /** * Updates an array property using a string index */ int phalcon_update_property_array_string(zval *object, char *property, unsigned int property_length, char *index, unsigned int index_length, zval *value TSRMLS_DC) { zval *tmp; int separated = 0; if (Z_TYPE_P(object) == IS_OBJECT) { phalcon_read_property(&tmp, object, property, property_length, PH_NOISY_CC); /** Separation only when refcount > 2 */ if (Z_REFCOUNT_P(tmp) > 2) { zval *new_zv; Z_DELREF_P(tmp); ALLOC_ZVAL(new_zv); INIT_PZVAL_COPY(new_zv, tmp); tmp = new_zv; zval_copy_ctor(new_zv); separated = 1; } /** Convert the value to array if not is an array */ if (Z_TYPE_P(tmp) != IS_ARRAY) { if (separated) { convert_to_array(tmp); } else { zval_ptr_dtor(&tmp); ALLOC_INIT_ZVAL(tmp); array_init(tmp); separated = 1; } } Z_ADDREF_P(value); zend_hash_update(Z_ARRVAL_P(tmp), index, index_length, &value, sizeof(zval *), NULL); if (separated) { phalcon_update_property_zval(object, property, property_length, tmp TSRMLS_CC); } zval_ptr_dtor(&tmp); } return SUCCESS; } /** * Appends a zval value to an array property */ int phalcon_update_property_array_append(zval *object, char *property, unsigned int property_length, zval *value TSRMLS_DC) { zval *tmp; int separated = 0; if (Z_TYPE_P(object) != IS_OBJECT) { return SUCCESS; } phalcon_read_property(&tmp, object, property, property_length, PH_NOISY_CC); /** Separation only when refcount > 2 */ if (Z_REFCOUNT_P(tmp) > 2) { zval *new_zv; Z_DELREF_P(tmp); ALLOC_ZVAL(new_zv); INIT_PZVAL_COPY(new_zv, tmp); tmp = new_zv; zval_copy_ctor(new_zv); separated = 1; } /** Convert the value to array if not is an array */ if (Z_TYPE_P(tmp) != IS_ARRAY) { if (separated) { convert_to_array(tmp); } else { zval_ptr_dtor(&tmp); ALLOC_INIT_ZVAL(tmp); array_init(tmp); separated = 1; } } Z_ADDREF_P(value); add_next_index_zval(tmp, value); if (separated) { phalcon_update_property_zval(object, property, property_length, tmp TSRMLS_CC); } zval_ptr_dtor(&tmp); return SUCCESS; } /** * Intializes an object property with an empty array */ int phalcon_update_property_empty_array(zend_class_entry *ce, zval *object, char *property_name, unsigned int property_length TSRMLS_DC) { zval *empty_array, *property; zend_class_entry *old_scope; ALLOC_INIT_ZVAL(empty_array); array_init(empty_array); Z_SET_REFCOUNT_P(empty_array, 0); old_scope = EG(scope); EG(scope) = ce; if (!Z_OBJ_HT_P(object)->write_property) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Property %s of class %s cannot be updated", property_name, ce->name); return FAILURE; } MAKE_STD_ZVAL(property); ZVAL_STRINGL(property, property_name, property_length, 0); #if PHP_VERSION_ID < 50400 Z_OBJ_HT_P(object)->write_property(object, property, empty_array TSRMLS_CC); #else Z_OBJ_HT_P(object)->write_property(object, property, empty_array, 0 TSRMLS_CC); #endif ZVAL_NULL(property); zval_ptr_dtor(&property); EG(scope) = old_scope; return SUCCESS; } /** * Check if a method is implemented on certain object */ int phalcon_method_exists(zval *object, zval *method_name TSRMLS_DC){ char *lcname; zend_class_entry *ce; unsigned long hash; if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); } else { if (Z_TYPE_P(object) == IS_STRING) { ce = zend_fetch_class(Z_STRVAL_P(object), Z_STRLEN_P(object), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); } else { return FAILURE; } } if (Z_TYPE_P(method_name) != IS_STRING) { return FAILURE; } lcname = zend_str_tolower_dup(Z_STRVAL_P(method_name), Z_STRLEN_P(method_name)); hash = zend_inline_hash_func(lcname, Z_STRLEN_P(method_name)+1); while (ce) { if (zend_hash_quick_exists(&ce->function_table, lcname, Z_STRLEN_P(method_name)+1, hash)) { efree(lcname); return SUCCESS; } ce = ce->parent; } efree(lcname); return FAILURE; } /** * Check if method exists on certain object using explicit char param */ int phalcon_method_exists_ex(zval *object, char *method_name, unsigned int method_len TSRMLS_DC){ zend_class_entry *ce; unsigned long hash; if (Z_TYPE_P(object) == IS_OBJECT) { ce = Z_OBJCE_P(object); } else { if (Z_TYPE_P(object) == IS_STRING) { ce = zend_fetch_class(Z_STRVAL_P(object), Z_STRLEN_P(object), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); } else { return FAILURE; } } hash = zend_inline_hash_func(method_name, method_len); ce = Z_OBJCE_P(object); while (ce) { if (zend_hash_quick_exists(&ce->function_table, method_name, method_len, hash)) { return SUCCESS; } ce = ce->parent; } return FAILURE; } /** * Query a static property value from a zend_class_entry */ int phalcon_read_static_property(zval **result, char *class_name, unsigned int class_length, char *property_name, unsigned int property_length TSRMLS_DC){ zend_class_entry **ce; if (zend_lookup_class(class_name, class_length, &ce TSRMLS_CC) == SUCCESS) { *result = zend_read_static_property(*ce, property_name, property_length, PH_FETCH_CLASS_SILENT); if (*result) { Z_ADDREF_PP(result); return SUCCESS; } } return FAILURE; } /** * Update a static property */ int phalcon_update_static_property(char *class_name, unsigned int class_length, char *name, unsigned int name_length, zval *value TSRMLS_DC){ zend_class_entry **ce; if (zend_lookup_class(class_name, class_length, &ce TSRMLS_CC) == SUCCESS) { return zend_update_static_property(*ce, name, name_length, value TSRMLS_CC); } return FAILURE; } /** * Creates a new instance dynamically. Call constructor without parameters */ int phalcon_create_instance(zval *return_value, zval *class_name TSRMLS_DC){ zend_class_entry *ce; if (Z_TYPE_P(class_name) != IS_STRING) { phalcon_throw_exception_string(phalcon_exception_ce, SL("Invalid class name") TSRMLS_CC); return FAILURE; } ce = zend_fetch_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); if (!ce) { return FAILURE; } object_init_ex(return_value, ce); if (phalcon_has_constructor(return_value TSRMLS_CC)) { if (phalcon_call_method(NULL, return_value, SL("__construct"), 0 PH_MEHASH_C TSRMLS_CC) == FAILURE) { return FAILURE; } } return SUCCESS; } /** * Creates a new instance dynamically calling constructor with parameters */ int phalcon_create_instance_params(zval *return_value, zval *class_name, zval *params TSRMLS_DC){ int i; zend_class_entry *ce; long param_count; zval **params_array; HashPosition pos; HashTable *params_hash; if (Z_TYPE_P(class_name) != IS_STRING) { phalcon_throw_exception_string(phalcon_exception_ce, SL("Invalid class name") TSRMLS_CC); return FAILURE; } if (Z_TYPE_P(params) != IS_ARRAY) { phalcon_throw_exception_string(phalcon_exception_ce, SL("Instantiation parameters must be an array") TSRMLS_CC); return FAILURE; } ce = zend_fetch_class(Z_STRVAL_P(class_name), Z_STRLEN_P(class_name), ZEND_FETCH_CLASS_DEFAULT TSRMLS_CC); if (!ce) { return FAILURE; } object_init_ex(return_value, ce); param_count = zend_hash_num_elements(Z_ARRVAL_P(params)); if (param_count > 0){ params_array = emalloc(sizeof(zval *) * param_count); params_hash = Z_ARRVAL_P(params); zend_hash_internal_pointer_reset_ex(params_hash, &pos); for (i=0; ; zend_hash_move_forward_ex(params_hash, &pos), i++) { zval ** item; if (zend_hash_get_current_data_ex(params_hash, (void**)&item, &pos) == FAILURE) { break; } params_array[i] = *item; } if (phalcon_has_constructor(return_value TSRMLS_CC)) { if (phalcon_call_method_params(NULL, return_value, SL("__construct"), (zend_uint) param_count, params_array, 0 PH_MEHASH_C TSRMLS_CC) == FAILURE) { efree(params_array); return FAILURE; } } efree(params_array); } else { if (phalcon_has_constructor(return_value TSRMLS_CC)) { if (phalcon_call_method(NULL, return_value, SL("__construct"), 0 PH_MEHASH_C TSRMLS_CC) == FAILURE) { return FAILURE; } } } return SUCCESS; } /** * Increments an object property */ int phalcon_property_incr(zval *object, char *property_name, unsigned int property_length TSRMLS_DC){ zval *tmp = NULL; zend_class_entry *ce; if (Z_TYPE_P(object) != IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } tmp = zend_read_property(ce, object, property_name, property_length, 0 TSRMLS_CC); if (tmp) { increment_function(tmp); } return SUCCESS; } /** * Decrements an object property */ int phalcon_property_decr(zval *object, char *property_name, unsigned int property_length TSRMLS_DC){ zval *tmp = NULL; zend_class_entry *ce; if (Z_TYPE_P(object) != IS_OBJECT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to assign property of non-object"); return FAILURE; } ce = Z_OBJCE_P(object); if (ce->parent) { ce = phalcon_lookup_class_ce(ce, property_name, property_length TSRMLS_CC); } tmp = zend_read_property(ce, object, property_name, property_length, 0 TSRMLS_CC); if (tmp) { decrement_function(tmp); } return SUCCESS; }
tmihalik/cphalcon
ext/mvc/view/engine/volt/parser.c
<reponame>tmihalik/cphalcon /* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is include which follows the "include" declaration ** in the input file. */ #include <stdio.h> // 38 "parser.lemon" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "parser.h" #include "scanner.h" #include "volt.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" #include "kernel/exception.h" static zval *phvolt_ret_literal_zval(int type, phvolt_parser_token *T, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (T) { add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_if_statement(zval *expr, zval *true_statements, zval *false_statements, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_IF); add_assoc_zval(ret, "expr", expr); add_assoc_zval(ret, "true_statements", true_statements); if (false_statements) { add_assoc_zval(ret, "false_statements", false_statements); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_elseif_statement(zval *expr, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_ELSEIF); add_assoc_zval(ret, "expr", expr); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_for_statement(phvolt_parser_token *variable, phvolt_parser_token *key, zval *expr, zval *if_expr, zval *block_statements, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_FOR); add_assoc_stringl(ret, "variable", variable->token, variable->token_len, 0); efree(variable); if (key) { add_assoc_stringl(ret, "key", key->token, key->token_len, 0); efree(key); } add_assoc_zval(ret, "expr", expr); if (if_expr) { add_assoc_zval(ret, "if_expr", if_expr); } add_assoc_zval(ret, "block_statements", block_statements); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_cache_statement(zval *expr, phvolt_parser_token *lifetime, zval *block_statements, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_CACHE); add_assoc_zval(ret, "expr", expr); if (lifetime) { add_assoc_stringl(ret, "lifetime", lifetime->token, lifetime->token_len, 0); efree(lifetime); } add_assoc_zval(ret, "block_statements", block_statements); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_set_statement(phvolt_parser_token *variable, zval *expr, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 5); add_assoc_long(ret, "type", PHVOLT_T_SET); add_assoc_stringl(ret, "variable", variable->token, variable->token_len, 0); efree(variable); add_assoc_zval(ret, "expr", expr); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_echo_statement(zval *expr, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 4); add_assoc_long(ret, "type", PHVOLT_T_ECHO); add_assoc_zval(ret, "expr", expr); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_block_statement(phvolt_parser_token *name, zval *block_statements, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_BLOCK); add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); if (block_statements) { add_assoc_zval(ret, "block_statements", block_statements); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_extends_statement(phvolt_parser_token *P, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 4); add_assoc_long(ret, "type", PHVOLT_T_EXTENDS); add_assoc_stringl(ret, "path", P->token, P->token_len, 0); efree(P); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_include_statement(phvolt_parser_token *P, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 4); add_assoc_long(ret, "type", PHVOLT_T_INCLUDE); add_assoc_stringl(ret, "path", P->token, P->token_len, 0); efree(P); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_do_statement(zval *expr, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 4); add_assoc_long(ret, "type", PHVOLT_T_DO); add_assoc_zval(ret, "expr", expr); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_autoescape_statement(int enable, zval *block_statements, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 5); add_assoc_long(ret, "type", PHVOLT_T_AUTOESCAPE); add_assoc_long(ret, "enable", enable); add_assoc_zval(ret, "block_statements", block_statements); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_empty_statement(phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 3); add_assoc_long(ret, "type", PHVOLT_T_EMPTY); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_break_statement(phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 3); add_assoc_long(ret, "type", PHVOLT_T_BREAK); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_continue_statement(phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init_size(ret, 3); add_assoc_long(ret, "type", PHVOLT_T_CONTINUE); Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_zval_list(zval *list_left, zval *right_list) { zval *ret; HashPosition pos; HashTable *list; MAKE_STD_ZVAL(ret); array_init(ret); if (list_left) { list = Z_ARRVAL_P(list_left); if (zend_hash_index_exists(list, 0)) { zend_hash_internal_pointer_reset_ex(list, &pos); for (;; zend_hash_move_forward_ex(list, &pos)) { zval ** item; if (zend_hash_get_current_data_ex(list, (void**) &item, &pos) == FAILURE) { break; } Z_ADDREF_PP(item); add_next_index_zval(ret, *item); } zval_ptr_dtor(&list_left); } else { add_next_index_zval(ret, list_left); } } add_next_index_zval(ret, right_list); return ret; } static zval *phvolt_ret_named_item(phvolt_parser_token *name, zval *expr, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "expr", expr); if (name != NULL) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_expr(int type, zval *left, zval *right, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (left) { add_assoc_zval(ret, "left", left); } if (right) { add_assoc_zval(ret, "right", right); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_slice(zval *left, zval *start, zval *end, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_SLICE); add_assoc_zval(ret, "left", left); if (start != NULL) { add_assoc_zval(ret, "start", start); } if (end != NULL) { add_assoc_zval(ret, "end", end); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } static zval *phvolt_ret_func_call(zval *expr, zval *arguments, phvolt_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHVOLT_T_FCALL); add_assoc_zval(ret, "name", expr); if (arguments) { add_assoc_zval(ret, "arguments", arguments); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } // 441 "parser.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** KKCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** KKNOCODE is a number of type KKCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** KKFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** KKACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** phvolt_KTOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** KKMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is phvolt_KTOKENTYPE. The entry in the union ** for base tokens is called "kk0". ** KKSTACKDEPTH is the maximum depth of the parser's stack. ** phvolt_ARG_SDECL A static variable declaration for the %extra_argument ** phvolt_ARG_PDECL A parameter declaration for the %extra_argument ** phvolt_ARG_STORE Code to store %extra_argument into kkpParser ** phvolt_ARG_FETCH Code to extract %extra_argument from kkpParser ** KKNSTATE the combined number of states. ** KKNRULE the number of rules in the grammar ** KKERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ #define KKCODETYPE unsigned char #define KKNOCODE 89 #define KKACTIONTYPE unsigned short int #define phvolt_KTOKENTYPE phvolt_parser_token* typedef union { phvolt_KTOKENTYPE kk0; zval* kk24; int kk177; } KKMINORTYPE; #define KKSTACKDEPTH 100 #define phvolt_ARG_SDECL phvolt_parser_status *status; #define phvolt_ARG_PDECL ,phvolt_parser_status *status #define phvolt_ARG_FETCH phvolt_parser_status *status = kkpParser->status #define phvolt_ARG_STORE kkpParser->status = status #define KKNSTATE 222 #define KKNRULE 91 #define KKERRORSYMBOL 61 #define KKERRSYMDT kk177 #define KK_NO_ACTION (KKNSTATE+KKNRULE+2) #define KK_ACCEPT_ACTION (KKNSTATE+KKNRULE+1) #define KK_ERROR_ACTION (KKNSTATE+KKNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < KKNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** KKNSTATE <= N < KKNSTATE+KKNRULE Reduce by rule N-KKNSTATE. ** ** N == KKNSTATE+KKNRULE A syntax error has occurred. ** ** N == KKNSTATE+KKNRULE+1 The parser accepts its input. ** ** N == KKNSTATE+KKNRULE+2 No such action. Denotes unused ** slots in the kk_action[] table. ** ** The action table is constructed as a single large table named kk_action[]. ** Given state S and lookahead X, the action is computed as ** ** kk_action[ kk_shift_ofst[S] + X ] ** ** If the index value kk_shift_ofst[S]+X is out of range or if the value ** kk_lookahead[kk_shift_ofst[S]+X] is not equal to X or if kk_shift_ofst[S] ** is equal to KK_SHIFT_USE_DFLT, it means that the action is not in the table ** and that kk_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the kk_reduce_ofst[] array is used in place of ** the kk_shift_ofst[] array and KK_REDUCE_USE_DFLT is used in place of ** KK_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** kk_action[] A single table containing all actions. ** kk_lookahead[] A table containing the lookahead for each entry in ** kk_action. Used to detect hash collisions. ** kk_shift_ofst[] For each state, the offset into kk_action for ** shifting terminals. ** kk_reduce_ofst[] For each state, the offset into kk_action for ** shifting non-terminals after a reduce. ** kk_default[] Default action for each state. */ static KKACTIONTYPE kk_action[] = { /* 0 */ 77, 55, 47, 49, 59, 57, 61, 67, 69, 71, /* 10 */ 73, 63, 65, 43, 41, 45, 39, 36, 51, 53, /* 20 */ 80, 80, 75, 75, 199, 134, 77, 55, 47, 49, /* 30 */ 59, 57, 61, 67, 69, 71, 73, 63, 65, 43, /* 40 */ 41, 45, 39, 36, 51, 53, 80, 222, 75, 118, /* 50 */ 26, 154, 43, 41, 45, 39, 36, 51, 53, 80, /* 60 */ 117, 75, 39, 36, 51, 53, 80, 190, 75, 28, /* 70 */ 75, 77, 55, 47, 49, 59, 57, 61, 67, 69, /* 80 */ 71, 73, 63, 65, 43, 41, 45, 39, 36, 51, /* 90 */ 53, 80, 169, 75, 184, 215, 210, 77, 55, 47, /* 100 */ 49, 59, 57, 61, 67, 69, 71, 73, 63, 65, /* 110 */ 43, 41, 45, 39, 36, 51, 53, 80, 32, 75, /* 120 */ 94, 110, 22, 77, 55, 47, 49, 59, 57, 61, /* 130 */ 67, 69, 71, 73, 63, 65, 43, 41, 45, 39, /* 140 */ 36, 51, 53, 80, 115, 75, 116, 293, 35, 77, /* 150 */ 55, 47, 49, 59, 57, 61, 67, 69, 71, 73, /* 160 */ 63, 65, 43, 41, 45, 39, 36, 51, 53, 80, /* 170 */ 120, 75, 77, 55, 47, 49, 59, 57, 61, 67, /* 180 */ 69, 71, 73, 63, 65, 43, 41, 45, 39, 36, /* 190 */ 51, 53, 80, 81, 75, 107, 91, 96, 105, 113, /* 200 */ 53, 80, 293, 75, 79, 314, 1, 2, 183, 4, /* 210 */ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 220 */ 15, 16, 17, 18, 294, 78, 86, 119, 122, 96, /* 230 */ 77, 55, 47, 49, 59, 57, 61, 67, 69, 71, /* 240 */ 73, 63, 65, 43, 41, 45, 39, 36, 51, 53, /* 250 */ 80, 106, 75, 90, 123, 143, 77, 55, 47, 49, /* 260 */ 59, 57, 61, 67, 69, 71, 73, 63, 65, 43, /* 270 */ 41, 45, 39, 36, 51, 53, 80, 294, 75, 131, /* 280 */ 138, 167, 77, 55, 47, 49, 59, 57, 61, 67, /* 290 */ 69, 71, 73, 63, 65, 43, 41, 45, 39, 36, /* 300 */ 51, 53, 80, 140, 75, 88, 89, 88, 104, 96, /* 310 */ 92, 96, 21, 81, 141, 146, 96, 96, 181, 108, /* 320 */ 147, 151, 77, 55, 47, 49, 59, 57, 61, 67, /* 330 */ 69, 71, 73, 63, 65, 43, 41, 45, 39, 36, /* 340 */ 51, 53, 80, 158, 75, 160, 161, 201, 77, 55, /* 350 */ 47, 49, 59, 57, 61, 67, 69, 71, 73, 63, /* 360 */ 65, 43, 41, 45, 39, 36, 51, 53, 80, 163, /* 370 */ 75, 164, 170, 217, 77, 55, 47, 49, 59, 57, /* 380 */ 61, 67, 69, 71, 73, 63, 65, 43, 41, 45, /* 390 */ 39, 36, 51, 53, 80, 174, 75, 47, 49, 59, /* 400 */ 57, 61, 67, 69, 71, 73, 63, 65, 43, 41, /* 410 */ 45, 39, 36, 51, 53, 80, 176, 75, 59, 57, /* 420 */ 61, 67, 69, 71, 73, 63, 65, 43, 41, 45, /* 430 */ 39, 36, 51, 53, 80, 178, 75, 185, 23, 183, /* 440 */ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, /* 450 */ 14, 15, 16, 17, 18, 29, 183, 4, 5, 6, /* 460 */ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, /* 470 */ 17, 18, 135, 183, 4, 5, 6, 7, 8, 9, /* 480 */ 10, 11, 12, 13, 14, 15, 16, 17, 18, 148, /* 490 */ 183, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 500 */ 13, 14, 15, 16, 17, 18, 155, 183, 4, 5, /* 510 */ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 520 */ 16, 17, 18, 171, 183, 4, 5, 6, 7, 8, /* 530 */ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, /* 540 */ 186, 183, 4, 5, 6, 7, 8, 9, 10, 11, /* 550 */ 12, 13, 14, 15, 16, 17, 18, 192, 183, 4, /* 560 */ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 570 */ 15, 16, 17, 18, 202, 183, 4, 5, 6, 7, /* 580 */ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, /* 590 */ 18, 211, 183, 4, 5, 6, 7, 8, 9, 10, /* 600 */ 11, 12, 13, 14, 15, 16, 17, 18, 218, 183, /* 610 */ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, /* 620 */ 14, 15, 16, 17, 18, 3, 4, 5, 6, 7, /* 630 */ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, /* 640 */ 18, 20, 144, 25, 27, 33, 130, 34, 19, 129, /* 650 */ 139, 96, 24, 96, 145, 189, 152, 191, 195, 159, /* 660 */ 179, 162, 165, 168, 179, 198, 205, 175, 177, 20, /* 670 */ 144, 31, 38, 33, 130, 40, 96, 182, 139, 96, /* 680 */ 207, 182, 145, 208, 152, 214, 221, 159, 118, 162, /* 690 */ 165, 168, 181, 181, 181, 175, 177, 20, 144, 117, /* 700 */ 181, 33, 130, 181, 30, 137, 139, 181, 136, 181, /* 710 */ 145, 181, 152, 121, 181, 159, 179, 162, 165, 168, /* 720 */ 179, 181, 181, 175, 177, 20, 144, 42, 181, 33, /* 730 */ 130, 96, 196, 182, 139, 181, 181, 182, 145, 150, /* 740 */ 152, 181, 181, 159, 179, 162, 165, 168, 181, 181, /* 750 */ 181, 175, 177, 20, 144, 44, 181, 33, 130, 96, /* 760 */ 149, 182, 139, 181, 156, 181, 145, 181, 152, 157, /* 770 */ 181, 159, 179, 162, 165, 168, 179, 181, 181, 175, /* 780 */ 177, 20, 144, 46, 181, 33, 130, 96, 172, 182, /* 790 */ 139, 181, 181, 182, 145, 181, 152, 181, 181, 159, /* 800 */ 179, 162, 165, 168, 181, 173, 181, 175, 177, 20, /* 810 */ 144, 48, 181, 33, 130, 96, 187, 182, 139, 181, /* 820 */ 193, 50, 145, 181, 152, 96, 181, 159, 179, 162, /* 830 */ 165, 168, 179, 188, 181, 175, 177, 20, 144, 52, /* 840 */ 181, 33, 130, 96, 203, 182, 139, 181, 181, 182, /* 850 */ 145, 181, 152, 194, 181, 159, 179, 162, 165, 168, /* 860 */ 181, 20, 144, 175, 177, 33, 130, 54, 212, 206, /* 870 */ 139, 96, 219, 182, 145, 197, 152, 181, 181, 159, /* 880 */ 179, 162, 165, 168, 179, 20, 144, 175, 177, 33, /* 890 */ 130, 181, 56, 204, 139, 58, 96, 182, 145, 96, /* 900 */ 152, 182, 132, 159, 60, 162, 165, 168, 96, 20, /* 910 */ 144, 175, 177, 33, 130, 181, 181, 213, 139, 62, /* 920 */ 181, 64, 145, 96, 152, 96, 181, 159, 66, 162, /* 930 */ 165, 168, 96, 20, 144, 175, 177, 33, 130, 181, /* 940 */ 68, 220, 139, 223, 96, 70, 145, 181, 152, 96, /* 950 */ 181, 159, 72, 162, 165, 168, 96, 20, 144, 175, /* 960 */ 177, 33, 130, 181, 74, 87, 139, 76, 96, 19, /* 970 */ 145, 96, 152, 181, 181, 159, 83, 162, 165, 168, /* 980 */ 96, 179, 37, 175, 177, 84, 126, 181, 85, 114, /* 990 */ 87, 181, 96, 95, 181, 97, 111, 96, 182, 133, /* 1000 */ 96, 142, 181, 96, 181, 96, 98, 37, 99, 153, /* 1010 */ 84, 82, 102, 96, 103, 87, 181, 181, 128, 166, /* 1020 */ 125, 100, 101, 96, 181, 180, 200, 181, 181, 96, /* 1030 */ 96, 124, 37, 99, 209, 84, 82, 102, 96, 103, /* 1040 */ 87, 181, 181, 181, 216, 97, 100, 101, 96, 181, /* 1050 */ 181, 181, 181, 181, 181, 181, 98, 37, 109, 181, /* 1060 */ 84, 82, 102, 181, 103, 87, 181, 181, 181, 112, /* 1070 */ 97, 100, 101, 181, 181, 181, 181, 181, 181, 181, /* 1080 */ 181, 98, 37, 99, 181, 84, 82, 102, 181, 103, /* 1090 */ 87, 181, 181, 127, 181, 97, 100, 101, 181, 181, /* 1100 */ 181, 181, 181, 181, 181, 181, 98, 37, 99, 181, /* 1110 */ 84, 82, 102, 181, 103, 87, 181, 181, 181, 181, /* 1120 */ 97, 100, 101, 181, 181, 181, 181, 181, 181, 181, /* 1130 */ 181, 98, 37, 93, 181, 84, 82, 102, 181, 103, /* 1140 */ 181, 181, 181, 181, 181, 97, 100, 101, 181, 181, /* 1150 */ 181, 181, 181, 181, 181, 181, 98, 181, 109, 181, /* 1160 */ 181, 181, 102, 181, 103, 181, 181, 181, 181, 181, /* 1170 */ 181, 100, 101, }; static KKCODETYPE kk_lookahead[] = { /* 0 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 10 */ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, /* 20 */ 23, 23, 25, 25, 27, 28, 3, 4, 5, 6, /* 30 */ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, /* 40 */ 17, 18, 19, 20, 21, 22, 23, 0, 25, 33, /* 50 */ 28, 28, 16, 17, 18, 19, 20, 21, 22, 23, /* 60 */ 44, 25, 19, 20, 21, 22, 23, 44, 25, 28, /* 70 */ 25, 3, 4, 5, 6, 7, 8, 9, 10, 11, /* 80 */ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, /* 90 */ 22, 23, 50, 25, 52, 27, 28, 3, 4, 5, /* 100 */ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 110 */ 16, 17, 18, 19, 20, 21, 22, 23, 28, 25, /* 120 */ 2, 2, 28, 3, 4, 5, 6, 7, 8, 9, /* 130 */ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* 140 */ 20, 21, 22, 23, 83, 25, 58, 58, 28, 3, /* 150 */ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, /* 160 */ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, /* 170 */ 2, 25, 3, 4, 5, 6, 7, 8, 9, 10, /* 180 */ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, /* 190 */ 21, 22, 23, 81, 25, 1, 1, 85, 86, 87, /* 200 */ 22, 23, 2, 25, 58, 62, 63, 64, 65, 66, /* 210 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, /* 220 */ 77, 78, 79, 80, 58, 81, 57, 83, 83, 85, /* 230 */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 240 */ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, /* 250 */ 23, 57, 25, 58, 58, 28, 3, 4, 5, 6, /* 260 */ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, /* 270 */ 17, 18, 19, 20, 21, 22, 23, 2, 25, 33, /* 280 */ 28, 28, 3, 4, 5, 6, 7, 8, 9, 10, /* 290 */ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, /* 300 */ 21, 22, 23, 33, 25, 81, 82, 81, 84, 85, /* 310 */ 84, 85, 81, 81, 37, 33, 85, 85, 39, 87, /* 320 */ 28, 28, 3, 4, 5, 6, 7, 8, 9, 10, /* 330 */ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, /* 340 */ 21, 22, 23, 28, 25, 46, 28, 28, 3, 4, /* 350 */ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 360 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 46, /* 370 */ 25, 28, 28, 28, 3, 4, 5, 6, 7, 8, /* 380 */ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, /* 390 */ 19, 20, 21, 22, 23, 28, 25, 5, 6, 7, /* 400 */ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, /* 410 */ 18, 19, 20, 21, 22, 23, 28, 25, 7, 8, /* 420 */ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, /* 430 */ 19, 20, 21, 22, 23, 28, 25, 28, 64, 65, /* 440 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, /* 450 */ 76, 77, 78, 79, 80, 64, 65, 66, 67, 68, /* 460 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, /* 470 */ 79, 80, 64, 65, 66, 67, 68, 69, 70, 71, /* 480 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 64, /* 490 */ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, /* 500 */ 75, 76, 77, 78, 79, 80, 64, 65, 66, 67, /* 510 */ 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, /* 520 */ 78, 79, 80, 64, 65, 66, 67, 68, 69, 70, /* 530 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, /* 540 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, /* 550 */ 74, 75, 76, 77, 78, 79, 80, 64, 65, 66, /* 560 */ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, /* 570 */ 77, 78, 79, 80, 64, 65, 66, 67, 68, 69, /* 580 */ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 590 */ 80, 64, 65, 66, 67, 68, 69, 70, 71, 72, /* 600 */ 73, 74, 75, 76, 77, 78, 79, 80, 64, 65, /* 610 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, /* 620 */ 76, 77, 78, 79, 80, 65, 66, 67, 68, 69, /* 630 */ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 640 */ 80, 27, 28, 29, 30, 31, 32, 81, 26, 81, /* 650 */ 36, 85, 26, 85, 40, 28, 42, 28, 28, 45, /* 660 */ 38, 47, 48, 49, 38, 28, 28, 53, 54, 27, /* 670 */ 28, 29, 81, 31, 32, 81, 85, 55, 36, 85, /* 680 */ 33, 55, 40, 34, 42, 28, 28, 45, 33, 47, /* 690 */ 48, 49, 88, 88, 88, 53, 54, 27, 28, 44, /* 700 */ 88, 31, 32, 88, 26, 35, 36, 88, 26, 88, /* 710 */ 40, 88, 42, 58, 88, 45, 38, 47, 48, 49, /* 720 */ 38, 88, 88, 53, 54, 27, 28, 81, 88, 31, /* 730 */ 32, 85, 26, 55, 36, 88, 88, 55, 40, 41, /* 740 */ 42, 88, 88, 45, 38, 47, 48, 49, 88, 88, /* 750 */ 88, 53, 54, 27, 28, 81, 88, 31, 32, 85, /* 760 */ 26, 55, 36, 88, 26, 88, 40, 88, 42, 43, /* 770 */ 88, 45, 38, 47, 48, 49, 38, 88, 88, 53, /* 780 */ 54, 27, 28, 81, 88, 31, 32, 85, 26, 55, /* 790 */ 36, 88, 88, 55, 40, 88, 42, 88, 88, 45, /* 800 */ 38, 47, 48, 49, 88, 51, 88, 53, 54, 27, /* 810 */ 28, 81, 88, 31, 32, 85, 26, 55, 36, 88, /* 820 */ 26, 81, 40, 88, 42, 85, 88, 45, 38, 47, /* 830 */ 48, 49, 38, 51, 88, 53, 54, 27, 28, 81, /* 840 */ 88, 31, 32, 85, 26, 55, 36, 88, 88, 55, /* 850 */ 40, 88, 42, 43, 88, 45, 38, 47, 48, 49, /* 860 */ 88, 27, 28, 53, 54, 31, 32, 81, 26, 1, /* 870 */ 36, 85, 26, 55, 40, 41, 42, 88, 88, 45, /* 880 */ 38, 47, 48, 49, 38, 27, 28, 53, 54, 31, /* 890 */ 32, 88, 81, 35, 36, 81, 85, 55, 40, 85, /* 900 */ 42, 55, 34, 45, 81, 47, 48, 49, 85, 27, /* 910 */ 28, 53, 54, 31, 32, 88, 88, 35, 36, 81, /* 920 */ 88, 81, 40, 85, 42, 85, 88, 45, 81, 47, /* 930 */ 48, 49, 85, 27, 28, 53, 54, 31, 32, 88, /* 940 */ 81, 35, 36, 0, 85, 81, 40, 88, 42, 85, /* 950 */ 88, 45, 81, 47, 48, 49, 85, 27, 28, 53, /* 960 */ 54, 31, 32, 88, 81, 3, 36, 81, 85, 26, /* 970 */ 40, 85, 42, 88, 88, 45, 81, 47, 48, 49, /* 980 */ 85, 38, 20, 53, 54, 23, 24, 88, 81, 2, /* 990 */ 3, 88, 85, 81, 88, 33, 81, 85, 55, 81, /* 1000 */ 85, 81, 88, 85, 88, 85, 44, 20, 46, 81, /* 1010 */ 23, 24, 50, 85, 52, 3, 88, 88, 56, 81, /* 1020 */ 33, 59, 60, 85, 88, 81, 81, 88, 88, 85, /* 1030 */ 85, 44, 20, 46, 81, 23, 24, 50, 85, 52, /* 1040 */ 3, 88, 88, 88, 81, 33, 59, 60, 85, 88, /* 1050 */ 88, 88, 88, 88, 88, 88, 44, 20, 46, 88, /* 1060 */ 23, 24, 50, 88, 52, 3, 88, 88, 88, 57, /* 1070 */ 33, 59, 60, 88, 88, 88, 88, 88, 88, 88, /* 1080 */ 88, 44, 20, 46, 88, 23, 24, 50, 88, 52, /* 1090 */ 3, 88, 88, 56, 88, 33, 59, 60, 88, 88, /* 1100 */ 88, 88, 88, 88, 88, 88, 44, 20, 46, 88, /* 1110 */ 23, 24, 50, 88, 52, 3, 88, 88, 88, 88, /* 1120 */ 33, 59, 60, 88, 88, 88, 88, 88, 88, 88, /* 1130 */ 88, 44, 20, 46, 88, 23, 24, 50, 88, 52, /* 1140 */ 88, 88, 88, 88, 88, 33, 59, 60, 88, 88, /* 1150 */ 88, 88, 88, 88, 88, 88, 44, 88, 46, 88, /* 1160 */ 88, 88, 50, 88, 52, 88, 88, 88, 88, 88, /* 1170 */ 88, 59, 60, }; #define KK_SHIFT_USE_DFLT (-4) static short kk_shift_ofst[] = { /* 0 */ 622, 47, 943, -4, -4, -4, -4, -4, -4, -4, /* 10 */ -4, -4, -4, -4, -4, -4, -4, -4, -4, 930, /* 20 */ 1062, 94, 622, 626, 614, 22, -4, 41, 622, 678, /* 30 */ 642, 90, -4, 1062, 120, -4, 1062, 1062, 178, 1062, /* 40 */ 178, 1062, 43, 1062, 43, 1062, 43, 1062, 411, 1062, /* 50 */ 411, 1062, 178, 1062, -2, 1062, 392, 1062, 36, 962, /* 60 */ 36, 1062, 36, 1062, 36, 1062, 36, 1062, 36, 1062, /* 70 */ 36, 1062, 36, 1062, 36, 1062, -4, 987, 146, -4, /* 80 */ 1012, 371, 1062, 45, 1062, 169, -4, 1087, 371, 195, /* 90 */ -4, 1087, -4, 118, 1062, 371, -4, -4, -4, -4, /* 100 */ -4, -4, -4, -4, -4, 194, -4, 1112, -4, 119, /* 110 */ 1062, 371, -4, -4, 16, 88, -4, 89, 166, 168, /* 120 */ 655, -4, 196, -4, 200, 275, 1037, -4, -4, 178, /* 130 */ 246, 868, 1062, -3, 622, 682, 670, 252, -4, 270, /* 140 */ 277, 1062, 227, -4, -4, 282, 292, 706, 734, 698, /* 150 */ 293, -4, 1062, 23, 622, 738, 726, 315, -4, 299, /* 160 */ 318, -4, 323, 343, -4, 1062, 253, -4, 42, 344, /* 170 */ 622, 762, 754, 367, -4, 388, -4, 407, -4, 1062, /* 180 */ 279, -4, -4, -4, 409, 622, 790, 782, 627, -4, /* 190 */ 629, 622, 794, 810, 630, -4, 834, 637, -4, 1062, /* 200 */ 319, 622, 818, 858, 638, -4, 647, 649, 1062, 68, /* 210 */ 622, 842, 882, 657, -4, 1062, 345, 622, 846, 906, /* 220 */ 658, -4, }; #define KK_REDUCE_USE_DFLT (-1) static short kk_reduce_ofst[] = { /* 0 */ 143, -1, 560, -1, -1, -1, -1, -1, -1, -1, /* 10 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20 */ 231, -1, 374, 560, -1, -1, -1, -1, 391, 560, /* 30 */ -1, -1, -1, 566, -1, -1, 568, 591, -1, 594, /* 40 */ -1, 646, -1, 674, -1, 702, -1, 730, -1, 740, /* 50 */ -1, 758, -1, 786, -1, 811, -1, 814, -1, 823, /* 60 */ -1, 838, -1, 840, -1, 847, -1, 859, -1, 864, /* 70 */ -1, 871, -1, 883, -1, 886, -1, 144, -1, -1, /* 80 */ 112, -1, 895, -1, 907, -1, -1, 224, -1, -1, /* 90 */ -1, 226, -1, -1, 912, -1, -1, -1, -1, -1, /* 100 */ -1, -1, -1, -1, -1, -1, -1, 232, -1, -1, /* 110 */ 915, -1, -1, -1, 61, -1, -1, -1, -1, -1, /* 120 */ 145, -1, -1, -1, -1, -1, 895, -1, -1, -1, /* 130 */ -1, -1, 918, -1, 408, 560, -1, -1, -1, -1, /* 140 */ -1, 920, -1, -1, -1, -1, -1, 425, 560, -1, /* 150 */ -1, -1, 928, -1, 442, 560, -1, -1, -1, -1, /* 160 */ -1, -1, -1, -1, -1, 938, -1, -1, -1, -1, /* 170 */ 459, 560, -1, -1, -1, -1, -1, -1, -1, 944, /* 180 */ -1, -1, -1, -1, -1, 476, 560, -1, -1, -1, /* 190 */ -1, 493, 560, -1, -1, -1, -1, -1, -1, 945, /* 200 */ -1, 510, 560, -1, -1, -1, -1, -1, 953, -1, /* 210 */ 527, 560, -1, -1, -1, 963, -1, 544, 560, -1, /* 220 */ -1, -1, }; static KKACTIONTYPE kk_default[] = { /* 0 */ 313, 313, 313, 224, 226, 227, 228, 229, 230, 231, /* 10 */ 232, 233, 234, 235, 236, 237, 238, 239, 240, 313, /* 20 */ 313, 313, 313, 313, 313, 313, 241, 313, 313, 313, /* 30 */ 313, 313, 242, 313, 313, 243, 313, 313, 263, 313, /* 40 */ 265, 313, 266, 313, 267, 313, 268, 313, 269, 313, /* 50 */ 270, 313, 271, 313, 272, 313, 273, 313, 274, 313, /* 60 */ 277, 313, 278, 313, 279, 313, 280, 313, 281, 313, /* 70 */ 282, 313, 283, 313, 284, 313, 285, 313, 313, 289, /* 80 */ 313, 304, 313, 286, 313, 313, 287, 313, 298, 313, /* 90 */ 288, 313, 295, 308, 313, 297, 299, 306, 307, 308, /* 100 */ 309, 310, 311, 312, 296, 313, 300, 313, 302, 308, /* 110 */ 313, 305, 301, 303, 313, 313, 290, 313, 313, 313, /* 120 */ 313, 291, 313, 292, 307, 306, 313, 275, 276, 264, /* 130 */ 313, 313, 313, 313, 313, 313, 313, 313, 244, 313, /* 140 */ 313, 313, 313, 248, 249, 313, 313, 313, 313, 313, /* 150 */ 313, 251, 313, 313, 313, 313, 313, 313, 253, 313, /* 160 */ 313, 255, 313, 313, 256, 313, 313, 257, 313, 313, /* 170 */ 313, 313, 313, 313, 258, 313, 260, 313, 261, 313, /* 180 */ 313, 250, 262, 225, 313, 313, 313, 313, 313, 259, /* 190 */ 313, 313, 313, 313, 313, 254, 313, 313, 252, 313, /* 200 */ 313, 313, 313, 313, 313, 245, 313, 313, 313, 313, /* 210 */ 313, 313, 313, 313, 246, 313, 313, 313, 313, 313, /* 220 */ 313, 247, }; #define KK_SZ_ACTTAB (sizeof(kk_action)/sizeof(kk_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef KKFALLBACK static const KKCODETYPE kkFallback[] = { }; #endif /* KKFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct kkStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ KKMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct kkStackEntry kkStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct kkParser { int kkidx; /* Index of top element in stack */ int kkerrcnt; /* Shifts left before out of the error */ phvolt_ARG_SDECL /* A place to hold %extra_argument */ kkStackEntry kkstack[KKSTACKDEPTH]; /* The parser's stack */ }; typedef struct kkParser kkParser; #ifndef NDEBUG #include <stdio.h> static FILE *kkTraceFILE = 0; static char *kkTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ void phvolt_Trace(FILE *TraceFILE, char *zTracePrompt){ kkTraceFILE = TraceFILE; kkTracePrompt = zTracePrompt; if( kkTraceFILE==0 ) kkTracePrompt = 0; else if( kkTracePrompt==0 ) kkTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *kkTokenName[] = { "$", "COMMA", "COLON", "SBRACKET_OPEN", "RANGE", "AND", "OR", "IS", "EQUALS", "NOTEQUALS", "LESS", "GREATER", "GREATEREQUAL", "LESSEQUAL", "IDENTICAL", "NOTIDENTICAL", "DIVIDE", "TIMES", "MOD", "PLUS", "MINUS", "CONCAT", "PIPE", "BRACKET_OPEN", "NOT", "DOT", "OPEN_DELIMITER", "IF", "CLOSE_DELIMITER", "ENDIF", "ELSE", "ELSEIF", "FOR", "IDENTIFIER", "IN", "ENDFOR", "SET", "ASSIGN", "OPEN_EDELIMITER", "CLOSE_EDELIMITER", "BLOCK", "ENDBLOCK", "CACHE", "ENDCACHE", "INTEGER", "EXTENDS", "STRING", "INCLUDE", "DO", "AUTOESCAPE", "FALSE", "ENDAUTOESCAPE", "TRUE", "BREAK", "CONTINUE", "RAW_FRAGMENT", "DEFINED", "BRACKET_CLOSE", "SBRACKET_CLOSE", "DOUBLE", "NULL", "error", "program", "volt_language", "statement_list", "statement", "raw_fragment", "if_statement", "elseif_statement", "for_statement", "set_statement", "echo_statement", "block_statement", "cache_statement", "extends_statement", "include_statement", "do_statement", "autoescape_statement", "break_statement", "continue_statement", "empty_statement", "expr", "array_list", "slice_offset", "array_item", "function_call", "argument_list", "argument_item", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *kkRuleName[] = { /* 0 */ "program ::= volt_language", /* 1 */ "volt_language ::= statement_list", /* 2 */ "statement_list ::= statement_list statement", /* 3 */ "statement_list ::= statement", /* 4 */ "statement ::= raw_fragment", /* 5 */ "statement ::= if_statement", /* 6 */ "statement ::= elseif_statement", /* 7 */ "statement ::= for_statement", /* 8 */ "statement ::= set_statement", /* 9 */ "statement ::= echo_statement", /* 10 */ "statement ::= block_statement", /* 11 */ "statement ::= cache_statement", /* 12 */ "statement ::= extends_statement", /* 13 */ "statement ::= include_statement", /* 14 */ "statement ::= do_statement", /* 15 */ "statement ::= autoescape_statement", /* 16 */ "statement ::= break_statement", /* 17 */ "statement ::= continue_statement", /* 18 */ "statement ::= empty_statement", /* 19 */ "if_statement ::= OPEN_DELIMITER IF expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDIF CLOSE_DELIMITER", /* 20 */ "if_statement ::= OPEN_DELIMITER IF expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ELSE CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDIF CLOSE_DELIMITER", /* 21 */ "elseif_statement ::= OPEN_DELIMITER ELSEIF expr CLOSE_DELIMITER", /* 22 */ "for_statement ::= OPEN_DELIMITER FOR IDENTIFIER IN expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDFOR CLOSE_DELIMITER", /* 23 */ "for_statement ::= OPEN_DELIMITER FOR IDENTIFIER IN expr IF expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDFOR CLOSE_DELIMITER", /* 24 */ "for_statement ::= OPEN_DELIMITER FOR IDENTIFIER COMMA IDENTIFIER IN expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDFOR CLOSE_DELIMITER", /* 25 */ "for_statement ::= OPEN_DELIMITER FOR IDENTIFIER COMMA IDENTIFIER IN expr IF expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDFOR CLOSE_DELIMITER", /* 26 */ "set_statement ::= OPEN_DELIMITER SET IDENTIFIER ASSIGN expr CLOSE_DELIMITER", /* 27 */ "empty_statement ::= OPEN_DELIMITER CLOSE_DELIMITER", /* 28 */ "echo_statement ::= OPEN_EDELIMITER expr CLOSE_EDELIMITER", /* 29 */ "block_statement ::= OPEN_DELIMITER BLOCK IDENTIFIER CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDBLOCK CLOSE_DELIMITER", /* 30 */ "block_statement ::= OPEN_DELIMITER BLOCK IDENTIFIER CLOSE_DELIMITER OPEN_DELIMITER ENDBLOCK CLOSE_DELIMITER", /* 31 */ "cache_statement ::= OPEN_DELIMITER CACHE expr CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDCACHE CLOSE_DELIMITER", /* 32 */ "cache_statement ::= OPEN_DELIMITER CACHE expr INTEGER CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDCACHE CLOSE_DELIMITER", /* 33 */ "extends_statement ::= OPEN_DELIMITER EXTENDS STRING CLOSE_DELIMITER", /* 34 */ "include_statement ::= OPEN_DELIMITER INCLUDE STRING CLOSE_DELIMITER", /* 35 */ "do_statement ::= OPEN_DELIMITER DO expr CLOSE_DELIMITER", /* 36 */ "autoescape_statement ::= OPEN_DELIMITER AUTOESCAPE FALSE CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDAUTOESCAPE CLOSE_DELIMITER", /* 37 */ "autoescape_statement ::= OPEN_DELIMITER AUTOESCAPE TRUE CLOSE_DELIMITER statement_list OPEN_DELIMITER ENDAUTOESCAPE CLOSE_DELIMITER", /* 38 */ "break_statement ::= OPEN_DELIMITER BREAK CLOSE_DELIMITER", /* 39 */ "continue_statement ::= OPEN_DELIMITER CONTINUE CLOSE_DELIMITER", /* 40 */ "raw_fragment ::= RAW_FRAGMENT", /* 41 */ "expr ::= MINUS expr", /* 42 */ "expr ::= expr MINUS expr", /* 43 */ "expr ::= expr PLUS expr", /* 44 */ "expr ::= expr TIMES expr", /* 45 */ "expr ::= expr DIVIDE expr", /* 46 */ "expr ::= expr MOD expr", /* 47 */ "expr ::= expr AND expr", /* 48 */ "expr ::= expr OR expr", /* 49 */ "expr ::= expr CONCAT expr", /* 50 */ "expr ::= expr PIPE expr", /* 51 */ "expr ::= expr RANGE expr", /* 52 */ "expr ::= expr EQUALS expr", /* 53 */ "expr ::= expr IS NOT DEFINED", /* 54 */ "expr ::= expr IS DEFINED", /* 55 */ "expr ::= expr IS expr", /* 56 */ "expr ::= expr NOTEQUALS expr", /* 57 */ "expr ::= expr IDENTICAL expr", /* 58 */ "expr ::= expr NOTIDENTICAL expr", /* 59 */ "expr ::= expr LESS expr", /* 60 */ "expr ::= expr GREATER expr", /* 61 */ "expr ::= expr GREATEREQUAL expr", /* 62 */ "expr ::= expr LESSEQUAL expr", /* 63 */ "expr ::= expr DOT expr", /* 64 */ "expr ::= NOT expr", /* 65 */ "expr ::= BRACKET_OPEN expr BRACKET_CLOSE", /* 66 */ "expr ::= SBRACKET_OPEN array_list SBRACKET_CLOSE", /* 67 */ "expr ::= expr SBRACKET_OPEN expr SBRACKET_CLOSE", /* 68 */ "expr ::= expr SBRACKET_OPEN COLON slice_offset SBRACKET_CLOSE", /* 69 */ "expr ::= expr SBRACKET_OPEN slice_offset COLON SBRACKET_CLOSE", /* 70 */ "expr ::= expr SBRACKET_OPEN slice_offset COLON slice_offset SBRACKET_CLOSE", /* 71 */ "slice_offset ::= INTEGER", /* 72 */ "slice_offset ::= IDENTIFIER", /* 73 */ "array_list ::= array_list COMMA array_item", /* 74 */ "array_list ::= array_item", /* 75 */ "array_item ::= STRING COLON expr", /* 76 */ "array_item ::= expr", /* 77 */ "expr ::= function_call", /* 78 */ "function_call ::= expr BRACKET_OPEN argument_list BRACKET_CLOSE", /* 79 */ "function_call ::= expr BRACKET_OPEN BRACKET_CLOSE", /* 80 */ "argument_list ::= argument_list COMMA argument_item", /* 81 */ "argument_list ::= argument_item", /* 82 */ "argument_item ::= expr", /* 83 */ "argument_item ::= STRING COLON expr", /* 84 */ "expr ::= IDENTIFIER", /* 85 */ "expr ::= INTEGER", /* 86 */ "expr ::= STRING", /* 87 */ "expr ::= DOUBLE", /* 88 */ "expr ::= NULL", /* 89 */ "expr ::= FALSE", /* 90 */ "expr ::= TRUE", }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *phvolt_TokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(kkTokenName)/sizeof(kkTokenName[0])) ){ return kkTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to phvolt_ and phvolt_Free. */ void *phvolt_Alloc(void *(*mallocProc)(size_t)){ kkParser *pParser; pParser = (kkParser*)(*mallocProc)( (size_t)sizeof(kkParser) ); if( pParser ){ pParser->kkidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "kkmajor" is the symbol code, and "kkpminor" is a pointer to ** the value. */ static void kk_destructor(KKCODETYPE kkmajor, KKMINORTYPE *kkpminor){ switch( kkmajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: // 517 "parser.lemon" { if ((kkpminor->kk0)) { if ((kkpminor->kk0)->free_flag) { efree((kkpminor->kk0)->token); } efree((kkpminor->kk0)); } } // 1206 "parser.c" break; case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: // 534 "parser.lemon" { zval_ptr_dtor(&(kkpminor->kk24)); } // 1234 "parser.c" break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int kk_pop_parser_stack(kkParser *pParser){ KKCODETYPE kkmajor; kkStackEntry *kktos = &pParser->kkstack[pParser->kkidx]; if( pParser->kkidx<0 ) return 0; #ifndef NDEBUG if( kkTraceFILE && pParser->kkidx>=0 ){ fprintf(kkTraceFILE,"%sPopping %s\n", kkTracePrompt, kkTokenName[kktos->major]); } #endif kkmajor = kktos->major; kk_destructor( kkmajor, &kktos->minor); pParser->kkidx--; return kkmajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: ** <ul> ** <li> A pointer to the parser. This should be a pointer ** obtained from phvolt_Alloc. ** <li> A pointer to a function used to reclaim memory obtained ** from malloc. ** </ul> */ void phvolt_Free( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ kkParser *pParser = (kkParser*)p; if( pParser==0 ) return; while( pParser->kkidx>=0 ) kk_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is KKNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return KK_NO_ACTION. */ static int kk_find_shift_action( kkParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->kkstack[pParser->kkidx].stateno; /* if( pParser->kkidx<0 ) return KK_NO_ACTION; */ i = kk_shift_ofst[stateno]; if( i==KK_SHIFT_USE_DFLT ){ return kk_default[stateno]; } if( iLookAhead==KKNOCODE ){ return KK_NO_ACTION; } i += iLookAhead; if( i<0 || i>=KK_SZ_ACTTAB || kk_lookahead[i]!=iLookAhead ){ #ifdef KKFALLBACK int iFallback; /* Fallback token */ if( iLookAhead<sizeof(kkFallback)/sizeof(kkFallback[0]) && (iFallback = kkFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE, "%sFALLBACK %s => %s\n", kkTracePrompt, kkTokenName[iLookAhead], kkTokenName[iFallback]); } #endif return kk_find_shift_action(pParser, iFallback); } #endif return kk_default[stateno]; }else{ return kk_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is KKNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return KK_NO_ACTION. */ static int kk_find_reduce_action( kkParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->kkstack[pParser->kkidx].stateno; i = kk_reduce_ofst[stateno]; if( i==KK_REDUCE_USE_DFLT ){ return kk_default[stateno]; } if( iLookAhead==KKNOCODE ){ return KK_NO_ACTION; } i += iLookAhead; if( i<0 || i>=KK_SZ_ACTTAB || kk_lookahead[i]!=iLookAhead ){ return kk_default[stateno]; }else{ return kk_action[i]; } } /* ** Perform a shift action. */ static void kk_shift( kkParser *kkpParser, /* The parser to be shifted */ int kkNewState, /* The new state to shift in */ int kkMajor, /* The major token to shift in */ KKMINORTYPE *kkpMinor /* Pointer ot the minor token to shift in */ ){ kkStackEntry *kktos; kkpParser->kkidx++; if( kkpParser->kkidx>=KKSTACKDEPTH ){ phvolt_ARG_FETCH; kkpParser->kkidx--; #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sStack Overflow!\n",kkTracePrompt); } #endif while( kkpParser->kkidx>=0 ) kk_pop_parser_stack(kkpParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ phvolt_ARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } kktos = &kkpParser->kkstack[kkpParser->kkidx]; kktos->stateno = kkNewState; kktos->major = kkMajor; kktos->minor = *kkpMinor; #ifndef NDEBUG if( kkTraceFILE && kkpParser->kkidx>0 ){ int i; fprintf(kkTraceFILE,"%sShift %d\n",kkTracePrompt,kkNewState); fprintf(kkTraceFILE,"%sStack:",kkTracePrompt); for(i=1; i<=kkpParser->kkidx; i++) fprintf(kkTraceFILE," %s",kkTokenName[kkpParser->kkstack[i].major]); fprintf(kkTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { KKCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } kkRuleInfo[] = { { 62, 1 }, { 63, 1 }, { 64, 2 }, { 64, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 65, 1 }, { 67, 8 }, { 67, 12 }, { 68, 4 }, { 69, 10 }, { 69, 12 }, { 69, 12 }, { 69, 14 }, { 70, 6 }, { 80, 2 }, { 71, 3 }, { 72, 8 }, { 72, 7 }, { 73, 8 }, { 73, 9 }, { 74, 4 }, { 75, 4 }, { 76, 4 }, { 77, 8 }, { 77, 8 }, { 78, 3 }, { 79, 3 }, { 66, 1 }, { 81, 2 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 4 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 3 }, { 81, 2 }, { 81, 3 }, { 81, 3 }, { 81, 4 }, { 81, 5 }, { 81, 5 }, { 81, 6 }, { 83, 1 }, { 83, 1 }, { 82, 3 }, { 82, 1 }, { 84, 3 }, { 84, 1 }, { 81, 1 }, { 85, 4 }, { 85, 3 }, { 86, 3 }, { 86, 1 }, { 87, 1 }, { 87, 3 }, { 81, 1 }, { 81, 1 }, { 81, 1 }, { 81, 1 }, { 81, 1 }, { 81, 1 }, { 81, 1 }, }; static void kk_accept(kkParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void kk_reduce( kkParser *kkpParser, /* The parser */ int kkruleno /* Number of the rule by which to reduce */ ){ int kkgoto; /* The next state */ int kkact; /* The next action */ KKMINORTYPE kkgotominor; /* The LHS of the rule reduced */ kkStackEntry *kkmsp; /* The top of the parser's stack */ int kksize; /* Amount to pop the stack */ phvolt_ARG_FETCH; kkmsp = &kkpParser->kkstack[kkpParser->kkidx]; #ifndef NDEBUG if( kkTraceFILE && kkruleno>=0 && kkruleno<sizeof(kkRuleName)/sizeof(kkRuleName[0]) ){ fprintf(kkTraceFILE, "%sReduce [%s].\n", kkTracePrompt, kkRuleName[kkruleno]); } #endif /* NDEBUG */ switch( kkruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** // <lineno> <grammarfile> ** { ... } // User supplied code ** // <lineno> <thisfile> ** break; */ case 0: // 526 "parser.lemon" { status->ret = kkmsp[0].minor.kk24; } // 1542 "parser.c" break; case 1: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 77: // 530 "parser.lemon" { kkgotominor.kk24 = kkmsp[0].minor.kk24; } // 1565 "parser.c" break; case 2: // 536 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_zval_list(kkmsp[-1].minor.kk24, kkmsp[0].minor.kk24); } // 1572 "parser.c" break; case 3: case 74: case 81: // 540 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_zval_list(NULL, kkmsp[0].minor.kk24); } // 1581 "parser.c" break; case 19: // 608 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_if_statement(kkmsp[-5].minor.kk24, kkmsp[-3].minor.kk24, NULL, status->scanner_state); kk_destructor(26,&kkmsp[-7].minor); kk_destructor(27,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(29,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1594 "parser.c" break; case 20: // 612 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_if_statement(kkmsp[-9].minor.kk24, kkmsp[-7].minor.kk24, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-11].minor); kk_destructor(27,&kkmsp[-10].minor); kk_destructor(28,&kkmsp[-8].minor); kk_destructor(26,&kkmsp[-6].minor); kk_destructor(30,&kkmsp[-5].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(29,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1610 "parser.c" break; case 21: // 618 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_elseif_statement(kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-3].minor); kk_destructor(31,&kkmsp[-2].minor); kk_destructor(28,&kkmsp[0].minor); } // 1620 "parser.c" break; case 22: // 624 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_for_statement(kkmsp[-7].minor.kk0, NULL, kkmsp[-5].minor.kk24, NULL, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-9].minor); kk_destructor(32,&kkmsp[-8].minor); kk_destructor(34,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(35,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1634 "parser.c" break; case 23: // 628 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_for_statement(kkmsp[-9].minor.kk0, NULL, kkmsp[-7].minor.kk24, kkmsp[-5].minor.kk24, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-11].minor); kk_destructor(32,&kkmsp[-10].minor); kk_destructor(34,&kkmsp[-8].minor); kk_destructor(27,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(35,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1649 "parser.c" break; case 24: // 632 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_for_statement(kkmsp[-7].minor.kk0, kkmsp[-9].minor.kk0, kkmsp[-5].minor.kk24, NULL, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-11].minor); kk_destructor(32,&kkmsp[-10].minor); kk_destructor(1,&kkmsp[-8].minor); kk_destructor(34,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(35,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1664 "parser.c" break; case 25: // 636 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_for_statement(kkmsp[-9].minor.kk0, kkmsp[-11].minor.kk0, kkmsp[-7].minor.kk24, kkmsp[-5].minor.kk24, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-13].minor); kk_destructor(32,&kkmsp[-12].minor); kk_destructor(1,&kkmsp[-10].minor); kk_destructor(34,&kkmsp[-8].minor); kk_destructor(27,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(35,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1680 "parser.c" break; case 26: // 642 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_set_statement(kkmsp[-3].minor.kk0, kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-5].minor); kk_destructor(36,&kkmsp[-4].minor); kk_destructor(37,&kkmsp[-2].minor); kk_destructor(28,&kkmsp[0].minor); } // 1691 "parser.c" break; case 27: // 648 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_empty_statement(status->scanner_state); kk_destructor(26,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1700 "parser.c" break; case 28: // 654 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_echo_statement(kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(38,&kkmsp[-2].minor); kk_destructor(39,&kkmsp[0].minor); } // 1709 "parser.c" break; case 29: // 660 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_block_statement(kkmsp[-5].minor.kk0, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-7].minor); kk_destructor(40,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(41,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1722 "parser.c" break; case 30: // 664 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_block_statement(kkmsp[-4].minor.kk0, NULL, status->scanner_state); kk_destructor(26,&kkmsp[-6].minor); kk_destructor(40,&kkmsp[-5].minor); kk_destructor(28,&kkmsp[-3].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(41,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1735 "parser.c" break; case 31: // 670 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_cache_statement(kkmsp[-5].minor.kk24, NULL, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-7].minor); kk_destructor(42,&kkmsp[-6].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(43,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1748 "parser.c" break; case 32: // 674 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_cache_statement(kkmsp[-6].minor.kk24, kkmsp[-5].minor.kk0, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-8].minor); kk_destructor(42,&kkmsp[-7].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(43,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1761 "parser.c" break; case 33: // 680 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_extends_statement(kkmsp[-1].minor.kk0, status->scanner_state); kk_destructor(26,&kkmsp[-3].minor); kk_destructor(45,&kkmsp[-2].minor); kk_destructor(28,&kkmsp[0].minor); } // 1771 "parser.c" break; case 34: // 686 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_include_statement(kkmsp[-1].minor.kk0, status->scanner_state); kk_destructor(26,&kkmsp[-3].minor); kk_destructor(47,&kkmsp[-2].minor); kk_destructor(28,&kkmsp[0].minor); } // 1781 "parser.c" break; case 35: // 692 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_do_statement(kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-3].minor); kk_destructor(48,&kkmsp[-2].minor); kk_destructor(28,&kkmsp[0].minor); } // 1791 "parser.c" break; case 36: // 698 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_autoescape_statement(0, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-7].minor); kk_destructor(49,&kkmsp[-6].minor); kk_destructor(50,&kkmsp[-5].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(51,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1805 "parser.c" break; case 37: // 702 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_autoescape_statement(1, kkmsp[-3].minor.kk24, status->scanner_state); kk_destructor(26,&kkmsp[-7].minor); kk_destructor(49,&kkmsp[-6].minor); kk_destructor(52,&kkmsp[-5].minor); kk_destructor(28,&kkmsp[-4].minor); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(51,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1819 "parser.c" break; case 38: // 708 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_break_statement(status->scanner_state); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(53,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1829 "parser.c" break; case 39: // 714 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_continue_statement(status->scanner_state); kk_destructor(26,&kkmsp[-2].minor); kk_destructor(54,&kkmsp[-1].minor); kk_destructor(28,&kkmsp[0].minor); } // 1839 "parser.c" break; case 40: // 720 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_RAW_FRAGMENT, kkmsp[0].minor.kk0, status->scanner_state); } // 1846 "parser.c" break; case 41: // 726 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_MINUS, NULL, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(20,&kkmsp[-1].minor); } // 1854 "parser.c" break; case 42: // 730 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_SUB, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(20,&kkmsp[-1].minor); } // 1862 "parser.c" break; case 43: // 734 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_ADD, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(19,&kkmsp[-1].minor); } // 1870 "parser.c" break; case 44: // 738 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_MUL, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(17,&kkmsp[-1].minor); } // 1878 "parser.c" break; case 45: // 742 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_DIV, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(16,&kkmsp[-1].minor); } // 1886 "parser.c" break; case 46: // 746 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_MOD, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(18,&kkmsp[-1].minor); } // 1894 "parser.c" break; case 47: // 750 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_AND, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(5,&kkmsp[-1].minor); } // 1902 "parser.c" break; case 48: // 754 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_OR, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(6,&kkmsp[-1].minor); } // 1910 "parser.c" break; case 49: // 758 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_CONCAT, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(21,&kkmsp[-1].minor); } // 1918 "parser.c" break; case 50: // 762 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_PIPE, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(22,&kkmsp[-1].minor); } // 1926 "parser.c" break; case 51: // 766 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_RANGE, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(4,&kkmsp[-1].minor); } // 1934 "parser.c" break; case 52: // 770 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_EQUALS, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(8,&kkmsp[-1].minor); } // 1942 "parser.c" break; case 53: // 774 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_NOT_ISSET, kkmsp[-3].minor.kk24, NULL, status->scanner_state); kk_destructor(7,&kkmsp[-2].minor); kk_destructor(24,&kkmsp[-1].minor); kk_destructor(56,&kkmsp[0].minor); } // 1952 "parser.c" break; case 54: // 778 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_ISSET, kkmsp[-2].minor.kk24, NULL, status->scanner_state); kk_destructor(7,&kkmsp[-1].minor); kk_destructor(56,&kkmsp[0].minor); } // 1961 "parser.c" break; case 55: // 782 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_IS, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(7,&kkmsp[-1].minor); } // 1969 "parser.c" break; case 56: // 786 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_NOTEQUALS, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(9,&kkmsp[-1].minor); } // 1977 "parser.c" break; case 57: // 790 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_IDENTICAL, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(14,&kkmsp[-1].minor); } // 1985 "parser.c" break; case 58: // 794 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_NOTIDENTICAL, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(15,&kkmsp[-1].minor); } // 1993 "parser.c" break; case 59: // 798 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_LESS, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(10,&kkmsp[-1].minor); } // 2001 "parser.c" break; case 60: // 802 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_GREATER, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(11,&kkmsp[-1].minor); } // 2009 "parser.c" break; case 61: // 806 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_GREATEREQUAL, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(12,&kkmsp[-1].minor); } // 2017 "parser.c" break; case 62: // 810 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_LESSEQUAL, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(13,&kkmsp[-1].minor); } // 2025 "parser.c" break; case 63: // 814 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_DOT, kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(25,&kkmsp[-1].minor); } // 2033 "parser.c" break; case 64: // 818 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_NOT, NULL, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(24,&kkmsp[-1].minor); } // 2041 "parser.c" break; case 65: // 822 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_ENCLOSED, kkmsp[-1].minor.kk24, NULL, status->scanner_state); kk_destructor(23,&kkmsp[-2].minor); kk_destructor(57,&kkmsp[0].minor); } // 2050 "parser.c" break; case 66: // 826 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_ARRAY, kkmsp[-1].minor.kk24, NULL, status->scanner_state); kk_destructor(3,&kkmsp[-2].minor); kk_destructor(58,&kkmsp[0].minor); } // 2059 "parser.c" break; case 67: // 830 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_expr(PHVOLT_T_ARRAYACCESS, kkmsp[-3].minor.kk24, kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(3,&kkmsp[-2].minor); kk_destructor(58,&kkmsp[0].minor); } // 2068 "parser.c" break; case 68: // 834 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_slice(kkmsp[-4].minor.kk24, NULL, kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(3,&kkmsp[-3].minor); kk_destructor(2,&kkmsp[-2].minor); kk_destructor(58,&kkmsp[0].minor); } // 2078 "parser.c" break; case 69: // 838 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_slice(kkmsp[-4].minor.kk24, kkmsp[-2].minor.kk24, NULL, status->scanner_state); kk_destructor(3,&kkmsp[-3].minor); kk_destructor(2,&kkmsp[-1].minor); kk_destructor(58,&kkmsp[0].minor); } // 2088 "parser.c" break; case 70: // 842 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_slice(kkmsp[-5].minor.kk24, kkmsp[-3].minor.kk24, kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(3,&kkmsp[-4].minor); kk_destructor(2,&kkmsp[-2].minor); kk_destructor(58,&kkmsp[0].minor); } // 2098 "parser.c" break; case 71: case 85: // 848 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_INTEGER, kkmsp[0].minor.kk0, status->scanner_state); } // 2106 "parser.c" break; case 72: case 84: // 852 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_IDENTIFIER, kkmsp[0].minor.kk0, status->scanner_state); } // 2114 "parser.c" break; case 73: case 80: // 858 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_zval_list(kkmsp[-2].minor.kk24, kkmsp[0].minor.kk24); kk_destructor(1,&kkmsp[-1].minor); } // 2123 "parser.c" break; case 75: case 83: // 868 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_named_item(kkmsp[-2].minor.kk0, kkmsp[0].minor.kk24, status->scanner_state); kk_destructor(2,&kkmsp[-1].minor); } // 2132 "parser.c" break; case 76: case 82: // 872 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_named_item(NULL, kkmsp[0].minor.kk24, status->scanner_state); } // 2140 "parser.c" break; case 78: // 882 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_func_call(kkmsp[-3].minor.kk24, kkmsp[-1].minor.kk24, status->scanner_state); kk_destructor(23,&kkmsp[-2].minor); kk_destructor(57,&kkmsp[0].minor); } // 2149 "parser.c" break; case 79: // 886 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_func_call(kkmsp[-2].minor.kk24, NULL, status->scanner_state); kk_destructor(23,&kkmsp[-1].minor); kk_destructor(57,&kkmsp[0].minor); } // 2158 "parser.c" break; case 86: // 918 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_STRING, kkmsp[0].minor.kk0, status->scanner_state); } // 2165 "parser.c" break; case 87: // 922 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_DOUBLE, kkmsp[0].minor.kk0, status->scanner_state); } // 2172 "parser.c" break; case 88: // 926 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_NULL, NULL, status->scanner_state); kk_destructor(60,&kkmsp[0].minor); } // 2180 "parser.c" break; case 89: // 930 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_FALSE, NULL, status->scanner_state); kk_destructor(50,&kkmsp[0].minor); } // 2188 "parser.c" break; case 90: // 934 "parser.lemon" { kkgotominor.kk24 = phvolt_ret_literal_zval(PHVOLT_T_TRUE, NULL, status->scanner_state); kk_destructor(52,&kkmsp[0].minor); } // 2196 "parser.c" break; }; kkgoto = kkRuleInfo[kkruleno].lhs; kksize = kkRuleInfo[kkruleno].nrhs; kkpParser->kkidx -= kksize; kkact = kk_find_reduce_action(kkpParser,kkgoto); if( kkact < KKNSTATE ){ kk_shift(kkpParser,kkact,kkgoto,&kkgotominor); }else if( kkact == KKNSTATE + KKNRULE + 1 ){ kk_accept(kkpParser); } } /* ** The following code executes when the parse fails */ static void kk_parse_failed( kkParser *kkpParser /* The parser */ ){ phvolt_ARG_FETCH; #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sFail!\n",kkTracePrompt); } #endif while( kkpParser->kkidx>=0 ) kk_pop_parser_stack(kkpParser); /* Here code is inserted which will be executed whenever the ** parser fails */ phvolt_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void kk_syntax_error( kkParser *kkpParser, /* The parser */ int kkmajor, /* The major type of the error token */ KKMINORTYPE kkminor /* The minor type of the error token */ ){ phvolt_ARG_FETCH; #define KTOKEN (kkminor.kk0) // 471 "parser.lemon" if (status->scanner_state->start_length) { { char *token_name = NULL; const phvolt_token_names *tokens = phvolt_tokens; int token_found = 0; int active_token = status->scanner_state->active_token; if (active_token) { do { if (tokens->code == active_token) { token_found = 1; token_name = tokens->name; break; } ++tokens; } while (tokens[0].code != 0); } if (!token_name) { token_found = 0; token_name = estrndup("UNKNOWN", strlen("UNKNOWN")); } status->syntax_error_len = 64 + strlen(token_name) + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); sprintf(status->syntax_error, "Syntax error, unexpected token %s in %s on line %d", token_name, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); if (!token_found) { if (token_name) { efree(token_name); } } } } else { status->syntax_error_len = 48 + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); sprintf(status->syntax_error, "Syntax error, unexpected EOF in %s", Z_STRVAL_P(status->scanner_state->active_file)); } status->status = PHVOLT_PARSING_FAILED; // 2284 "parser.c" phvolt_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void kk_accept( kkParser *kkpParser /* The parser */ ){ phvolt_ARG_FETCH; #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sAccept!\n",kkTracePrompt); } #endif while( kkpParser->kkidx>=0 ) kk_pop_parser_stack(kkpParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ phvolt_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "phvolt_Alloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ void phvolt_( void *kkp, /* The parser */ int kkmajor, /* The major token code number */ phvolt_KTOKENTYPE kkminor /* The value for the token */ phvolt_ARG_PDECL /* Optional %extra_argument parameter */ ){ KKMINORTYPE kkminorunion; int kkact; /* The parser action. */ int kkendofinput; /* True if we are at the end of input */ int kkerrorhit = 0; /* True if kkmajor has invoked an error */ kkParser *kkpParser; /* The parser */ /* (re)initialize the parser, if necessary */ kkpParser = (kkParser*)kkp; if( kkpParser->kkidx<0 ){ if( kkmajor==0 ) return; kkpParser->kkidx = 0; kkpParser->kkerrcnt = -1; kkpParser->kkstack[0].stateno = 0; kkpParser->kkstack[0].major = 0; } kkminorunion.kk0 = kkminor; kkendofinput = (kkmajor==0); phvolt_ARG_STORE; #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sInput %s\n",kkTracePrompt,kkTokenName[kkmajor]); } #endif do{ kkact = kk_find_shift_action(kkpParser,kkmajor); if( kkact<KKNSTATE ){ kk_shift(kkpParser,kkact,kkmajor,&kkminorunion); kkpParser->kkerrcnt--; if( kkendofinput && kkpParser->kkidx>=0 ){ kkmajor = 0; }else{ kkmajor = KKNOCODE; } }else if( kkact < KKNSTATE + KKNRULE ){ kk_reduce(kkpParser,kkact-KKNSTATE); }else if( kkact == KK_ERROR_ACTION ){ int kkmx; #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sSyntax Error!\n",kkTracePrompt); } #endif #ifdef KKERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( kkpParser->kkerrcnt<0 ){ kk_syntax_error(kkpParser,kkmajor,kkminorunion); } kkmx = kkpParser->kkstack[kkpParser->kkidx].major; if( kkmx==KKERRORSYMBOL || kkerrorhit ){ #ifndef NDEBUG if( kkTraceFILE ){ fprintf(kkTraceFILE,"%sDiscard input token %s\n", kkTracePrompt,kkTokenName[kkmajor]); } #endif kk_destructor(kkmajor,&kkminorunion); kkmajor = KKNOCODE; }else{ while( kkpParser->kkidx >= 0 && kkmx != KKERRORSYMBOL && (kkact = kk_find_shift_action(kkpParser,KKERRORSYMBOL)) >= KKNSTATE ){ kk_pop_parser_stack(kkpParser); } if( kkpParser->kkidx < 0 || kkmajor==0 ){ kk_destructor(kkmajor,&kkminorunion); kk_parse_failed(kkpParser); kkmajor = KKNOCODE; }else if( kkmx!=KKERRORSYMBOL ){ KKMINORTYPE u2; u2.KKERRSYMDT = 0; kk_shift(kkpParser,kkact,KKERRORSYMBOL,&u2); } } kkpParser->kkerrcnt = 3; kkerrorhit = 1; #else /* KKERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( kkpParser->kkerrcnt<=0 ){ kk_syntax_error(kkpParser,kkmajor,kkminorunion); } kkpParser->kkerrcnt = 3; kk_destructor(kkmajor,&kkminorunion); if( kkendofinput ){ kk_parse_failed(kkpParser); } kkmajor = KKNOCODE; #endif }else{ kk_accept(kkpParser); kkmajor = KKNOCODE; } }while( kkmajor!=KKNOCODE && kkpParser->kkidx>=0 ); return; } /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2012 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ const phvolt_token_names phvolt_tokens[] = { { PHVOLT_T_INTEGER, "INTEGER" }, { PHVOLT_T_DOUBLE, "DOUBLE" }, { PHVOLT_T_STRING, "STRING" }, { PHVOLT_T_IDENTIFIER, "IDENTIFIER" }, { PHVOLT_T_MINUS, "MINUS" }, { PHVOLT_T_ADD, "+" }, { PHVOLT_T_SUB, "-" }, { PHVOLT_T_MUL, "*" }, { PHVOLT_T_DIV, "/" }, { PHVOLT_T_MOD, "%%" }, { PHVOLT_T_NOT, "!" }, { PHVOLT_T_CONCAT, "~" }, { PHVOLT_T_AND, "AND" }, { PHVOLT_T_OR, "OR" }, { PHVOLT_T_DOT, "DOT" }, { PHVOLT_T_COMMA, "COMMA" }, { PHVOLT_T_EQUALS, "EQUALS" }, { PHVOLT_T_NOTEQUALS, "NOT EQUALS" }, { PHVOLT_T_IDENTICAL, "IDENTICAL" }, { PHVOLT_T_NOTIDENTICAL, "NOT IDENTICAL" }, { PHVOLT_T_NOT, "NOT" }, { PHVOLT_T_RANGE, "RANGE" }, { PHVOLT_T_COLON, "COLON" }, { PHVOLT_T_LESS, "<" }, { PHVOLT_T_LESSEQUAL, "<=" }, { PHVOLT_T_GREATER, ">" }, { PHVOLT_T_GREATEREQUAL, ">=" }, { PHVOLT_T_BRACKET_OPEN, "(" }, { PHVOLT_T_BRACKET_CLOSE, ")" }, { PHVOLT_T_SBRACKET_OPEN, "[" }, { PHVOLT_T_SBRACKET_CLOSE, "]" }, { PHVOLT_T_OPEN_DELIMITER, "{%" }, { PHVOLT_T_CLOSE_DELIMITER, "%}" }, { PHVOLT_T_OPEN_EDELIMITER, "{{" }, { PHVOLT_T_CLOSE_EDELIMITER, "}}" }, { PHVOLT_T_IF, "IF" }, { PHVOLT_T_ELSE, "ELSE" }, { PHVOLT_T_ELSEIF, "ELSEIF" }, { PHVOLT_T_ENDIF, "ENDIF" }, { PHVOLT_T_FOR, "FOR" }, { PHVOLT_T_IN, "IN" }, { PHVOLT_T_ENDFOR, "ENDFOR" }, { PHVOLT_T_SET, "SET" }, { PHVOLT_T_ASSIGN, "ASSIGN" }, { PHVOLT_T_BLOCK, "BLOCK" }, { PHVOLT_T_ENDBLOCK, "ENDBLOCK" }, { PHVOLT_T_CACHE, "CACHE" }, { PHVOLT_T_ENDCACHE, "ENDCACHE" }, { PHVOLT_T_EXTENDS, "EXTENDS" }, { PHVOLT_T_IS, "IS" }, { PHVOLT_T_DEFINED, "DEFINED" }, { PHVOLT_T_INCLUDE, "INCLUDE" }, { PHVOLT_T_DO, "DO" }, { PHVOLT_T_IGNORE, "WHITESPACE" }, { PHVOLT_T_AUTOESCAPE, "AUTOESCAPE" }, { PHVOLT_T_ENDAUTOESCAPE, "ENDAUTOESCAPE" }, { PHVOLT_T_CONTINUE, "CONTINUE" }, { PHVOLT_T_BREAK, "BREAK" }, { 0, NULL } }; /** * Wrapper to alloc memory within the parser */ static void *phvolt_wrapper_alloc(size_t bytes){ return emalloc(bytes); } /** * Wrapper to free memory within the parser */ static void phvolt_wrapper_free(void *pointer){ efree(pointer); } /** * Creates a parser_token to be passed to the parser */ static void phvolt_parse_with_token(void* phvolt_parser, int opcode, int parsercode, phvolt_scanner_token *token, phvolt_parser_status *parser_status){ phvolt_parser_token *pToken; pToken = emalloc(sizeof(phvolt_parser_token)); pToken->opcode = opcode; pToken->token = token->value; pToken->token_len = token->len; pToken->free_flag = 1; phvolt_(phvolt_parser, parsercode, pToken, parser_status); } /** * Creates an error message */ static void phvolt_create_error_msg(phvolt_parser_status *parser_status, char *message){ unsigned int length = (128 + Z_STRLEN_P(parser_status->scanner_state->active_file)); char *str = emalloc(sizeof(char) * length); snprintf(str, length, "%s in %s on line %d", message, Z_STRVAL_P(parser_status->scanner_state->active_file), parser_status->scanner_state->active_line); str[length - 1] = '\0'; parser_status->syntax_error = estrndup(str, strlen(str)); efree(str); } /** * Creates an error message when it's triggered by the scanner */ static void phvolt_scanner_error_msg(phvolt_parser_status *parser_status, zval **error_msg TSRMLS_DC){ char *error, *error_part; phvolt_scanner_state *state = parser_status->scanner_state; PHALCON_INIT_VAR(*error_msg); if (state->start) { error = emalloc(sizeof(char) * 64 + state->start_length + Z_STRLEN_P(state->active_file)); if (state->start_length > 16) { error_part = estrndup(state->start, 16); sprintf(error, "Parsing error before '%s...' in %s on line %d", error_part, Z_STRVAL_P(state->active_file), state->active_line); efree(error_part); } else { sprintf(error, "Parsing error before '%s' in %s on line %d", state->start, Z_STRVAL_P(state->active_file), state->active_line); } ZVAL_STRING(*error_msg, error, 1); } else { error = emalloc(sizeof(char) * (32 + Z_STRLEN_P(state->active_file))); sprintf(error, "Parsing error near to EOF in %s", Z_STRVAL_P(state->active_file)); ZVAL_STRING(*error_msg, error, 1); } efree(error); } /** * Receives the volt code tokenizes and parses it */ int phvolt_parse_view(zval *result, zval *view_code, zval *template_path TSRMLS_DC){ zval *error_msg = NULL; ZVAL_NULL(result); if (Z_TYPE_P(view_code) != IS_STRING) { phalcon_throw_exception_string(phalcon_mvc_view_exception_ce, SL("View code must be a string") TSRMLS_CC); return FAILURE; } if(phvolt_internal_parse_view(&result, view_code, template_path, &error_msg TSRMLS_CC) == FAILURE){ phalcon_throw_exception_string(phalcon_mvc_view_exception_ce, Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg) TSRMLS_CC); return FAILURE; } return SUCCESS; } /** * Checks whether the token has only blank characters */ int phvolt_is_blank_string(phvolt_scanner_token *token){ char *marker = token->value; unsigned int ch, i; for (i = 0; i < token->len; i++) { ch = *marker; if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r' && ch != 11) { return 0; } marker++; } return 1; } /** * Parses a volt template returning an intermediate array representation */ int phvolt_internal_parse_view(zval **result, zval *view_code, zval *template_path, zval **error_msg TSRMLS_DC) { char *error; phvolt_scanner_state *state; phvolt_scanner_token token; int scanner_status, status = SUCCESS; phvolt_parser_status *parser_status = NULL; void* phvolt_parser; /** Check if the view has code */ if (!Z_STRVAL_P(view_code)) { PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, "View code cannot be null", 1); return FAILURE; } if (!Z_STRLEN_P(view_code)) { array_init(*result); return SUCCESS; } /** Start the reentrant parser */ phvolt_parser = phvolt_Alloc(phvolt_wrapper_alloc); parser_status = emalloc(sizeof(phvolt_parser_status)); state = emalloc(sizeof(phvolt_scanner_state)); parser_status->status = PHVOLT_PARSING_OK; parser_status->scanner_state = state; parser_status->ret = NULL; parser_status->syntax_error = NULL; /** Initialize the scanner state */ state->active_token = 0; state->start = Z_STRVAL_P(view_code); state->mode = PHVOLT_MODE_RAW; state->raw_buffer = emalloc(sizeof(char) * PHVOLT_RAW_BUFFER_SIZE); state->raw_buffer_size = PHVOLT_RAW_BUFFER_SIZE; state->raw_buffer_cursor = 0; state->active_file = template_path; state->active_line = 1; state->statement_position = 0; state->extends_mode = 0; state->block_level = 0; state->start_length = 0; state->end = state->start; while(0 <= (scanner_status = phvolt_get_token(state, &token))) { state->active_token = token.opcode; state->start_length = (Z_STRVAL_P(view_code) + Z_STRLEN_P(view_code) - state->start); switch(token.opcode){ case PHVOLT_T_IGNORE: break; case PHVOLT_T_ADD: phvolt_(phvolt_parser, PHVOLT_PLUS, NULL, parser_status); break; case PHVOLT_T_SUB: phvolt_(phvolt_parser, PHVOLT_MINUS, NULL, parser_status); break; case PHVOLT_T_MUL: phvolt_(phvolt_parser, PHVOLT_TIMES, NULL, parser_status); break; case PHVOLT_T_DIV: phvolt_(phvolt_parser, PHVOLT_DIVIDE, NULL, parser_status); break; case PHVOLT_T_MOD: phvolt_(phvolt_parser, PHVOLT_MOD, NULL, parser_status); break; case PHVOLT_T_AND: phvolt_(phvolt_parser, PHVOLT_AND, NULL, parser_status); break; case PHVOLT_T_OR: phvolt_(phvolt_parser, PHVOLT_OR, NULL, parser_status); break; case PHVOLT_T_IS: phvolt_(phvolt_parser, PHVOLT_IS, NULL, parser_status); break; case PHVOLT_T_EQUALS: phvolt_(phvolt_parser, PHVOLT_EQUALS, NULL, parser_status); break; case PHVOLT_T_NOTEQUALS: phvolt_(phvolt_parser, PHVOLT_NOTEQUALS, NULL, parser_status); break; case PHVOLT_T_LESS: phvolt_(phvolt_parser, PHVOLT_LESS, NULL, parser_status); break; case PHVOLT_T_GREATER: phvolt_(phvolt_parser, PHVOLT_GREATER, NULL, parser_status); break; case PHVOLT_T_GREATEREQUAL: phvolt_(phvolt_parser, PHVOLT_GREATEREQUAL, NULL, parser_status); break; case PHVOLT_T_LESSEQUAL: phvolt_(phvolt_parser, PHVOLT_LESSEQUAL, NULL, parser_status); break; case PHVOLT_T_IDENTICAL: phvolt_(phvolt_parser, PHVOLT_IDENTICAL, NULL, parser_status); break; case PHVOLT_T_NOTIDENTICAL: phvolt_(phvolt_parser, PHVOLT_NOTIDENTICAL, NULL, parser_status); break; case PHVOLT_T_NOT: phvolt_(phvolt_parser, PHVOLT_NOT, NULL, parser_status); break; case PHVOLT_T_DOT: phvolt_(phvolt_parser, PHVOLT_DOT, NULL, parser_status); break; case PHVOLT_T_CONCAT: phvolt_(phvolt_parser, PHVOLT_CONCAT, NULL, parser_status); break; case PHVOLT_T_RANGE: phvolt_(phvolt_parser, PHVOLT_RANGE, NULL, parser_status); break; case PHVOLT_T_PIPE: phvolt_(phvolt_parser, PHVOLT_PIPE, NULL, parser_status); break; case PHVOLT_T_COMMA: phvolt_(phvolt_parser, PHVOLT_COMMA, NULL, parser_status); break; case PHVOLT_T_COLON: phvolt_(phvolt_parser, PHVOLT_COLON, NULL, parser_status); break; case PHVOLT_T_BRACKET_OPEN: phvolt_(phvolt_parser, PHVOLT_BRACKET_OPEN, NULL, parser_status); break; case PHVOLT_T_BRACKET_CLOSE: phvolt_(phvolt_parser, PHVOLT_BRACKET_CLOSE, NULL, parser_status); break; case PHVOLT_T_SBRACKET_OPEN: phvolt_(phvolt_parser, PHVOLT_SBRACKET_OPEN, NULL, parser_status); break; case PHVOLT_T_SBRACKET_CLOSE: phvolt_(phvolt_parser, PHVOLT_SBRACKET_CLOSE, NULL, parser_status); break; case PHVOLT_T_OPEN_DELIMITER: phvolt_(phvolt_parser, PHVOLT_OPEN_DELIMITER, NULL, parser_status); break; case PHVOLT_T_CLOSE_DELIMITER: phvolt_(phvolt_parser, PHVOLT_CLOSE_DELIMITER, NULL, parser_status); break; case PHVOLT_T_OPEN_EDELIMITER: if (state->extends_mode == 1 && state->block_level == 0){ phvolt_create_error_msg(parser_status, "Child templates only may contain blocks"); parser_status->status = PHVOLT_PARSING_FAILED; break; } phvolt_(phvolt_parser, PHVOLT_OPEN_EDELIMITER, NULL, parser_status); break; case PHVOLT_T_CLOSE_EDELIMITER: phvolt_(phvolt_parser, PHVOLT_CLOSE_EDELIMITER, NULL, parser_status); break; case PHVOLT_T_NULL: phvolt_(phvolt_parser, PHVOLT_NULL, NULL, parser_status); break; case PHVOLT_T_TRUE: phvolt_(phvolt_parser, PHVOLT_TRUE, NULL, parser_status); break; case PHVOLT_T_FALSE: phvolt_(phvolt_parser, PHVOLT_FALSE, NULL, parser_status); break; case PHVOLT_T_INTEGER: phvolt_parse_with_token(phvolt_parser, PHVOLT_T_INTEGER, PHVOLT_INTEGER, &token, parser_status); break; case PHVOLT_T_DOUBLE: phvolt_parse_with_token(phvolt_parser, PHVOLT_T_DOUBLE, PHVOLT_DOUBLE, &token, parser_status); break; case PHVOLT_T_STRING: phvolt_parse_with_token(phvolt_parser, PHVOLT_T_STRING, PHVOLT_STRING, &token, parser_status); break; case PHVOLT_T_IDENTIFIER: phvolt_parse_with_token(phvolt_parser, PHVOLT_T_IDENTIFIER, PHVOLT_IDENTIFIER, &token, parser_status); break; case PHVOLT_T_IF: if (state->extends_mode == 1 && state->block_level == 0){ phvolt_create_error_msg(parser_status, "Child templates only may contain blocks"); parser_status->status = PHVOLT_PARSING_FAILED; break; } else { state->block_level++; } phvolt_(phvolt_parser, PHVOLT_IF, NULL, parser_status); break; case PHVOLT_T_ELSE: phvolt_(phvolt_parser, PHVOLT_ELSE, NULL, parser_status); break; case PHVOLT_T_ELSEIF: phvolt_(phvolt_parser, PHVOLT_ELSEIF, NULL, parser_status); break; case PHVOLT_T_ENDIF: state->block_level--; phvolt_(phvolt_parser, PHVOLT_ENDIF, NULL, parser_status); break; case PHVOLT_T_FOR: if (state->extends_mode == 1 && state->block_level == 0){ phvolt_create_error_msg(parser_status, "Child templates only may contain blocks"); parser_status->status = PHVOLT_PARSING_FAILED; break; } else { state->block_level++; } phvolt_(phvolt_parser, PHVOLT_FOR, NULL, parser_status); break; case PHVOLT_T_IN: phvolt_(phvolt_parser, PHVOLT_IN, NULL, parser_status); break; case PHVOLT_T_ENDFOR: state->block_level--; phvolt_(phvolt_parser, PHVOLT_ENDFOR, NULL, parser_status); break; case PHVOLT_T_RAW_FRAGMENT: if (state->extends_mode == 1 && state->block_level == 0){ if(!phvolt_is_blank_string(&token)){ phvolt_create_error_msg(parser_status, "Child templates only may contain blocks"); parser_status->status = PHVOLT_PARSING_FAILED; } efree(token.value); break; } else { if(!phvolt_is_blank_string(&token)){ state->statement_position++; } } phvolt_parse_with_token(phvolt_parser, PHVOLT_T_RAW_FRAGMENT, PHVOLT_RAW_FRAGMENT, &token, parser_status); break; case PHVOLT_T_SET: if (state->extends_mode == 1 && state->block_level == 0){ phvolt_create_error_msg(parser_status, "Child templates only may contain blocks"); parser_status->status = PHVOLT_PARSING_FAILED; break; } phvolt_(phvolt_parser, PHVOLT_SET, NULL, parser_status); break; case PHVOLT_T_ASSIGN: phvolt_(phvolt_parser, PHVOLT_ASSIGN, NULL, parser_status); break; case PHVOLT_T_BLOCK: if(state->block_level > 0){ phvolt_create_error_msg(parser_status, "Embedding blocks into other blocks is not supported"); parser_status->status = PHVOLT_PARSING_FAILED; break; } else { state->block_level++; } phvolt_(phvolt_parser, PHVOLT_BLOCK, NULL, parser_status); break; case PHVOLT_T_ENDBLOCK: state->block_level--; phvolt_(phvolt_parser, PHVOLT_ENDBLOCK, NULL, parser_status); break; case PHVOLT_T_CACHE: phvolt_(phvolt_parser, PHVOLT_CACHE, NULL, parser_status); break; case PHVOLT_T_ENDCACHE: phvolt_(phvolt_parser, PHVOLT_ENDCACHE, NULL, parser_status); break; case PHVOLT_T_INCLUDE: phvolt_(phvolt_parser, PHVOLT_INCLUDE, NULL, parser_status); break; case PHVOLT_T_DEFINED: phvolt_(phvolt_parser, PHVOLT_DEFINED, NULL, parser_status); break; case PHVOLT_T_DO: phvolt_(phvolt_parser, PHVOLT_DO, NULL, parser_status); break; case PHVOLT_T_AUTOESCAPE: phvolt_(phvolt_parser, PHVOLT_AUTOESCAPE, NULL, parser_status); break; case PHVOLT_T_ENDAUTOESCAPE: phvolt_(phvolt_parser, PHVOLT_ENDAUTOESCAPE, NULL, parser_status); break; case PHVOLT_T_BREAK: phvolt_(phvolt_parser, PHVOLT_BREAK, NULL, parser_status); break; case PHVOLT_T_CONTINUE: phvolt_(phvolt_parser, PHVOLT_CONTINUE, NULL, parser_status); break; case PHVOLT_T_EXTENDS: if (state->statement_position != 1) { phvolt_create_error_msg(parser_status, "Extends statement must be placed at the first line in the template"); parser_status->status = PHVOLT_PARSING_FAILED; break; } else { state->extends_mode = 1; } phvolt_(phvolt_parser, PHVOLT_EXTENDS, NULL, parser_status); break; default: parser_status->status = PHVOLT_PARSING_FAILED; if (!*error_msg) { error = emalloc(sizeof(char) * (48 + Z_STRLEN_P(state->active_file))); sprintf(error, "Scanner: unknown opcode %d on in %s line %d", token.opcode, Z_STRVAL_P(state->active_file), state->active_line); PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, error, 1); efree(error); } break; } if (parser_status->status != PHVOLT_PARSING_OK) { status = FAILURE; break; } state->end = state->start; } if (status != FAILURE) { switch (scanner_status) { case PHVOLT_SCANNER_RETCODE_ERR: case PHVOLT_SCANNER_RETCODE_IMPOSSIBLE: if (!*error_msg) { phvolt_scanner_error_msg(parser_status, error_msg TSRMLS_CC); } status = FAILURE; break; default: phvolt_(phvolt_parser, 0, NULL, parser_status); } } state->active_token = 0; state->start = NULL; efree(state->raw_buffer); if (parser_status->status != PHVOLT_PARSING_OK) { status = FAILURE; if (parser_status->syntax_error) { if (!*error_msg) { PHALCON_INIT_VAR(*error_msg); ZVAL_STRING(*error_msg, parser_status->syntax_error, 1); } efree(parser_status->syntax_error); } } phvolt_Free(phvolt_parser, phvolt_wrapper_free); if (status != FAILURE) { if (parser_status->status == PHVOLT_PARSING_OK) { if (parser_status->ret) { ZVAL_ZVAL(*result, parser_status->ret, 0, 0); ZVAL_NULL(parser_status->ret); zval_ptr_dtor(&parser_status->ret); } else { array_init(*result); } } } efree(parser_status); efree(state); return status; }
tmihalik/cphalcon
ext/db/index.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/exception.h" #include "kernel/fcall.h" /** * Phalcon\Db\Index * * Allows to define indexes to be used on tables. Indexes are a common way * to enhance database performance. An index allows the database server to find * and retrieve specific rows much faster than it could do without an index */ /** * Phalcon\Db\Index initializer */ PHALCON_INIT_CLASS(Phalcon_Db_Index){ PHALCON_REGISTER_CLASS(Phalcon\\Db, Index, db_index, phalcon_db_index_method_entry, 0); zend_declare_property_null(phalcon_db_index_ce, SL("_indexName"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_db_index_ce, SL("_columns"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_db_index_ce TSRMLS_CC, 1, phalcon_db_indexinterface_ce); return SUCCESS; } /** * Phalcon\Db\Index constructor * * @param string $indexName * @param array $columns */ PHP_METHOD(Phalcon_Db_Index, __construct){ zval *index_name, *columns; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index_name, &columns) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_indexName"), index_name TSRMLS_CC); phalcon_update_property_zval(this_ptr, SL("_columns"), columns TSRMLS_CC); } /** * Gets the index name * * @return string */ PHP_METHOD(Phalcon_Db_Index, getName){ RETURN_MEMBER(this_ptr, "_indexName"); } /** * Gets the columns that comprends the index * * @return array */ PHP_METHOD(Phalcon_Db_Index, getColumns){ RETURN_MEMBER(this_ptr, "_columns"); } /** * Restore a Phalcon\Db\Index object from export * * @param array $data * @return Phalcon\Db\IndexInterface */ PHP_METHOD(Phalcon_Db_Index, __set_state){ zval *data, *index_name, *columns, *index; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &data) == FAILURE) { RETURN_MM_NULL(); } if (!phalcon_array_isset_string(data, SS("_indexName"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "_indexName parameter is required"); return; } if (!phalcon_array_isset_string(data, SS("_columns"))) { PHALCON_THROW_EXCEPTION_STR(phalcon_db_exception_ce, "_columns parameter is required"); return; } PHALCON_OBS_VAR(index_name); phalcon_array_fetch_string(&index_name, data, SL("_indexName"), PH_NOISY_CC); PHALCON_OBS_VAR(columns); phalcon_array_fetch_string(&columns, data, SL("_columns"), PH_NOISY_CC); /** * Return a Phalcon\Db\Index as part of the returning state */ PHALCON_INIT_VAR(index); object_init_ex(index, phalcon_db_index_ce); PHALCON_CALL_METHOD_PARAMS_2_NORETURN(index, "__construct", index_name, columns); RETURN_CTOR(index); }
tmihalik/cphalcon
ext/kernel/file.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "php_main.h" #include "main/php_streams.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/php_filestat.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/concat.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" /** * Checks if a file exist * */ int phalcon_file_exists(zval *filename TSRMLS_DC){ if (Z_TYPE_P(filename) != IS_STRING) { return FAILURE; } if (VCWD_ACCESS(Z_STRVAL_P(filename), F_OK) == 0) { return SUCCESS; } return FAILURE; } /** * Compares two file paths returning 1 if the first mtime is greater or equal than the second */ int phalcon_compare_mtime(zval *filename1, zval *filename2 TSRMLS_DC){ php_stream_statbuf statbuffer1, statbuffer2; if (Z_TYPE_P(filename1) != IS_STRING || Z_TYPE_P(filename2) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid arguments supplied for compare_mtime()"); return 0; } if (php_stream_stat_path_ex(Z_STRVAL_P(filename1), 0, &statbuffer1, NULL)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "mstat failed for %s", Z_STRVAL_P(filename1)); return 0; } if (php_stream_stat_path_ex(Z_STRVAL_P(filename2), 0, &statbuffer2, NULL)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "mstat failed for %s", Z_STRVAL_P(filename2)); return 0; } return (int) (statbuffer1.sb.st_mtime >= statbuffer2.sb.st_mtime); } /** * Executes the filemtime function without function lookup */ void phalcon_fast_filemtime(zval *return_value, zval *filename TSRMLS_DC){ if (Z_TYPE_P(filename) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid arguments supplied for fast_filemtime()"); return; } php_stat(Z_STRVAL_P(filename), (php_stat_len) Z_STRLEN_P(filename), FS_MTIME, return_value TSRMLS_CC); } /** * Adds a trailing directory separator if the path doesn't have it */ void phalcon_fix_path(zval **return_value, zval *path, zval *directory_separator TSRMLS_DC) { if (Z_TYPE_P(path) != IS_STRING || Z_TYPE_P(directory_separator) != IS_STRING) { return; } if (Z_STRLEN_P(path) > 0 && Z_STRLEN_P(directory_separator) > 0) { if (Z_STRVAL_P(path)[Z_STRLEN_P(path)-1] != Z_STRVAL_P(directory_separator)[0]) { PHALCON_CONCAT_VV(*return_value, path, directory_separator); return; } } zval_ptr_dtor(return_value); *return_value = path; Z_ADDREF_P(path); } /** * Replaces directory separators by the virtual separator */ void phalcon_prepare_virtual_path(zval *return_value, zval *path, zval *virtual_separator TSRMLS_DC) { unsigned int i; unsigned char ch; smart_str virtual_str = {0}; if (Z_TYPE_P(path) != IS_STRING || Z_TYPE_P(virtual_separator) != IS_STRING) { return; } for (i = 0; i < Z_STRLEN_P(path); i++) { ch = Z_STRVAL_P(path)[i]; if (ch == '/' || ch == '\\' || ch == ':') { smart_str_appendl(&virtual_str, Z_STRVAL_P(virtual_separator), Z_STRLEN_P(virtual_separator)); continue; } smart_str_appendc(&virtual_str, ch); } smart_str_0(&virtual_str); if (virtual_str.len) { RETURN_STRINGL(virtual_str.c, virtual_str.len, 0); } else { smart_str_free(&virtual_str); RETURN_EMPTY_STRING(); } }
tmihalik/cphalcon
ext/mvc/micro/collection.c
<filename>ext/mvc/micro/collection.c<gh_stars>1-10 /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/fcall.h" /** * Phalcon\Mvc\Micro\Collection * * Groups handlers as controllers */ /** * Phalcon\Mvc\Micro\Collection initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Micro_Collection){ PHALCON_REGISTER_CLASS(Phalcon\\Mvc\\Micro, Collection, mvc_micro_collection, phalcon_mvc_micro_collection_method_entry, 0); zend_declare_property_null(phalcon_mvc_micro_collection_ce, SL("_handlers"), ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } PHP_METHOD(Phalcon_Mvc_Micro_Collection, _addMap){ } /** * Maps a route to a handler that only matches if the HTTP method is GET * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, get){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "get", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is POST * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, post){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "post", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is PUT * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, put){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "put", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is PATCH * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, patch){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "patch", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is HEAD * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, head){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "head", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is DELETE * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, delete){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "delete", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); } /** * Maps a route to a handler that only matches if the HTTP method is OPTIONS * * @param string $routePattern * @param callable $handler * @return Phalcon\Mvc\Router\RouteInterface */ PHP_METHOD(Phalcon_Mvc_Micro_Collection, options){ zval *route_pattern, *handler, *method, *route; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &route_pattern, &handler) == FAILURE) { RETURN_MM_NULL(); } PHALCON_INIT_VAR(method); ZVAL_STRING(method, "options", 1); PHALCON_INIT_VAR(route); PHALCON_CALL_METHOD_PARAMS_3(route, this_ptr, "_addmap", method, route_pattern, handler); RETURN_CCTOR(route); }
tmihalik/cphalcon
ext/paginator/adapter/nativearray.c
<filename>ext/paginator/adapter/nativearray.c /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/array.h" #include "kernel/exception.h" #include "kernel/fcall.h" #include "kernel/operators.h" /** * Phalcon\Paginator\Adapter\NativeArray * * Component of pagination by array data * */ /** * Phalcon\Paginator\Adapter\NativeArray initializer */ PHALCON_INIT_CLASS(Phalcon_Paginator_Adapter_NativeArray){ PHALCON_REGISTER_CLASS(Phalcon\\Paginator\\Adapter, NativeArray, paginator_adapter_nativearray, phalcon_paginator_adapter_nativearray_method_entry, 0); zend_declare_property_null(phalcon_paginator_adapter_nativearray_ce, SL("_limitRows"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_paginator_adapter_nativearray_ce, SL("_config"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(phalcon_paginator_adapter_nativearray_ce, SL("_page"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_paginator_adapter_nativearray_ce TSRMLS_CC, 1, phalcon_paginator_adapterinterface_ce); return SUCCESS; } /** * Phalcon\Paginator\Adapter\NativeArray constructor * * @param array $config */ PHP_METHOD(Phalcon_Paginator_Adapter_NativeArray, __construct){ zval *config, *limit, *page; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &config) == FAILURE) { RETURN_MM_NULL(); } phalcon_update_property_zval(this_ptr, SL("_config"), config TSRMLS_CC); if (phalcon_array_isset_string(config, SS("limit"))) { PHALCON_OBS_VAR(limit); phalcon_array_fetch_string(&limit, config, SL("limit"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_limitRows"), limit TSRMLS_CC); } if (phalcon_array_isset_string(config, SS("page"))) { PHALCON_OBS_VAR(page); phalcon_array_fetch_string(&page, config, SL("page"), PH_NOISY_CC); phalcon_update_property_zval(this_ptr, SL("_page"), page TSRMLS_CC); } PHALCON_MM_RESTORE(); } /** * Set the current page number * * @param int $page */ PHP_METHOD(Phalcon_Paginator_Adapter_NativeArray, setCurrentPage){ zval *page; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &page) == FAILURE) { RETURN_NULL(); } phalcon_update_property_zval(this_ptr, SL("_page"), page TSRMLS_CC); } /** * Returns a slice of the resultset to show in the pagination * * @return stdClass */ PHP_METHOD(Phalcon_Paginator_Adapter_NativeArray, getPaginate){ zval *one, *show, *items, *page_number = NULL, *n, *page, *before_page_number; zval *start, *nn, *rounded_total, *total_pages = NULL; zval *div, *to_show, *compare = NULL, *next = NULL, *before = NULL, *res, *t_pages = NULL; zval *t0 = NULL; zval *r0 = NULL, *r1 = NULL; PHALCON_MM_GROW(); /** * TODO: Rewrite the whole method! */ PHALCON_INIT_VAR(one); ZVAL_LONG(one, 1); PHALCON_OBS_VAR(show); phalcon_read_property(&show, this_ptr, SL("_limitRows"), PH_NOISY_CC); PHALCON_OBS_VAR(t0); phalcon_read_property(&t0, this_ptr, SL("_config"), PH_NOISY_CC); PHALCON_OBS_VAR(items); phalcon_array_fetch_string(&items, t0, SL("data"), PH_NOISY_CC); PHALCON_OBS_VAR(page_number); phalcon_read_property(&page_number, this_ptr, SL("_page"), PH_NOISY_CC); if (Z_TYPE_P(page_number) == IS_NULL) { PHALCON_CPY_WRT(page_number, one); } if (Z_TYPE_P(items) != IS_ARRAY) { PHALCON_THROW_EXCEPTION_STR(phalcon_paginator_exception_ce, "Invalid data for paginator"); return; } PHALCON_INIT_VAR(n); phalcon_fast_count(n, items TSRMLS_CC); PHALCON_INIT_VAR(page); object_init(page); PHALCON_INIT_VAR(before_page_number); sub_function(before_page_number, page_number, one TSRMLS_CC); PHALCON_INIT_VAR(start); mul_function(start, show, before_page_number TSRMLS_CC); PHALCON_INIT_VAR(nn); sub_function(nn, n, one TSRMLS_CC); PHALCON_INIT_VAR(rounded_total); div_function(rounded_total, nn, show TSRMLS_CC); PHALCON_INIT_VAR(total_pages); PHALCON_CALL_FUNC_PARAMS_1(total_pages, "round", rounded_total); PHALCON_INIT_VAR(r0); PHALCON_CALL_FUNC_PARAMS_3(r0, "array_slice", items, start, show); phalcon_update_property_zval(page, SL("items"), r0 TSRMLS_CC); phalcon_update_property_zval(page, SL("first"), one TSRMLS_CC); PHALCON_INIT_VAR(div); div_function(div, n, show TSRMLS_CC); PHALCON_INIT_VAR(to_show); phalcon_add_function(to_show, start, show TSRMLS_CC); PHALCON_INIT_VAR(compare); is_smaller_function(compare, to_show, n TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_INIT_VAR(next); phalcon_add_function(next, page_number, one TSRMLS_CC); } else { if (PHALCON_IS_EQUAL(to_show, n)) { PHALCON_CPY_WRT(next, n); } else { PHALCON_INIT_NVAR(next); phalcon_add_function(next, div, one TSRMLS_CC); } PHALCON_INIT_VAR(r1); PHALCON_CALL_FUNC_PARAMS_1(r1, "intval", next); PHALCON_CPY_WRT(next, r1); } is_smaller_function(compare, total_pages, next TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_CPY_WRT(next, total_pages); } phalcon_update_property_zval(page, SL("next"), next TSRMLS_CC); is_smaller_function(compare, one, page_number TSRMLS_CC); if (PHALCON_IS_TRUE(compare)) { PHALCON_INIT_VAR(before); sub_function(before, page_number, one TSRMLS_CC); } else { PHALCON_CPY_WRT(before, one); } phalcon_update_property_zval(page, SL("before"), before TSRMLS_CC); phalcon_update_property_zval(page, SL("current"), page_number TSRMLS_CC); PHALCON_INIT_VAR(res); mod_function(res, n, show TSRMLS_CC); if (zend_is_true(res)) { PHALCON_INIT_VAR(t_pages); phalcon_add_function(t_pages, div, one TSRMLS_CC); } else { PHALCON_CPY_WRT(t_pages, div); } PHALCON_INIT_NVAR(total_pages); PHALCON_CALL_FUNC_PARAMS_1(total_pages, "intval", t_pages); phalcon_update_property_zval(page, SL("last"), total_pages TSRMLS_CC); phalcon_update_property_zval(page, SL("total_pages"), total_pages TSRMLS_CC); RETURN_CTOR(page); }
tmihalik/cphalcon
ext/logger/adapter/stream.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_phalcon.h" #include "phalcon.h" #include "Zend/zend_operators.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/array.h" #include "kernel/string.h" #include "kernel/exception.h" #include "kernel/fcall.h" #include "kernel/concat.h" #include "kernel/object.h" /** * Phalcon\Logger\Adapter\Stream * * Sends logs to a valid PHP stream * *<code> * $logger = new \Phalcon\Logger\Adapter\Stream("php://stderr"); * $logger->log("This is a message"); * $logger->log("This is an error", \Phalcon\Logger::ERROR); * $logger->error("This is another error"); *</code> */ /** * Phalcon\Logger\Adapter\Stream initializer */ PHALCON_INIT_CLASS(Phalcon_Logger_Adapter_Stream){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Logger\\Adapter, Stream, logger_adapter_stream, "phalcon\\logger\\adapter", phalcon_logger_adapter_stream_method_entry, 0); zend_declare_property_null(phalcon_logger_adapter_stream_ce, SL("_stream"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_logger_adapter_stream_ce TSRMLS_CC, 1, phalcon_logger_adapterinterface_ce); return SUCCESS; } /** * Phalcon\Logger\Adapter\Stream constructor * * @param string $name * @param array $options */ PHP_METHOD(Phalcon_Logger_Adapter_Stream, __construct){ zval *name, *options = NULL, *mode = NULL, *stream, *exception_message; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &name, &options) == FAILURE) { RETURN_MM_NULL(); } if (!options) { PHALCON_INIT_VAR(options); } if (phalcon_array_isset_string(options, SS("mode"))) { PHALCON_OBS_VAR(mode); phalcon_array_fetch_string(&mode, options, SL("mode"), PH_NOISY_CC); if (phalcon_memnstr_str(mode, SL("r") TSRMLS_CC)) { PHALCON_THROW_EXCEPTION_STR(phalcon_logger_exception_ce, "Stream must be opened in append or write mode"); return; } } else { PHALCON_INIT_NVAR(mode); ZVAL_STRING(mode, "ab", 1); } /** * We use 'fopen' to respect to open-basedir directive */ PHALCON_INIT_VAR(stream); PHALCON_CALL_FUNC_PARAMS_2(stream, "fopen", name, mode); if (!zend_is_true(stream)) { PHALCON_INIT_VAR(exception_message); PHALCON_CONCAT_SVS(exception_message, "Can't open stream '", name, "'"); PHALCON_THROW_EXCEPTION_ZVAL(phalcon_logger_exception_ce, exception_message); return; } phalcon_update_property_zval(this_ptr, SL("_stream"), stream TSRMLS_CC); PHALCON_MM_RESTORE(); } /** * Returns the internal formatter * * @return Phalcon\Logger\Formatter\Line */ PHP_METHOD(Phalcon_Logger_Adapter_Stream, getFormatter){ zval *formatter = NULL; PHALCON_MM_GROW(); PHALCON_OBS_VAR(formatter); phalcon_read_property(&formatter, this_ptr, SL("_formatter"), PH_NOISY_CC); if (Z_TYPE_P(formatter) != IS_OBJECT) { PHALCON_INIT_NVAR(formatter); object_init_ex(formatter, phalcon_logger_formatter_line_ce); PHALCON_CALL_METHOD_NORETURN(formatter, "__construct"); phalcon_update_property_zval(this_ptr, SL("_formatter"), formatter TSRMLS_CC); } RETURN_CCTOR(formatter); } /** * Writes the log to the stream itself * * @param string $message * @param int $type * @param int $time */ PHP_METHOD(Phalcon_Logger_Adapter_Stream, logInternal){ zval *message, *type, *time, *stream, *formatter, *applied_format; PHALCON_MM_GROW(); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzz", &message, &type, &time) == FAILURE) { RETURN_MM_NULL(); } PHALCON_OBS_VAR(stream); phalcon_read_property(&stream, this_ptr, SL("_stream"), PH_NOISY_CC); if (!zend_is_true(stream)) { PHALCON_THROW_EXCEPTION_STR(phalcon_logger_exception_ce, "Cannot send message to the log because it is invalid"); return; } PHALCON_INIT_VAR(formatter); PHALCON_CALL_METHOD(formatter, this_ptr, "getformatter"); PHALCON_INIT_VAR(applied_format); PHALCON_CALL_METHOD_PARAMS_3(applied_format, formatter, "format", message, type, time); PHALCON_CALL_FUNC_PARAMS_2_NORETURN("fwrite", stream, applied_format); PHALCON_MM_RESTORE(); } /** * Closes the logger * * @return boolean */ PHP_METHOD(Phalcon_Logger_Adapter_Stream, close){ zval *stream, *success; PHALCON_MM_GROW(); PHALCON_OBS_VAR(stream); phalcon_read_property(&stream, this_ptr, SL("_stream"), PH_NOISY_CC); PHALCON_INIT_VAR(success); PHALCON_CALL_FUNC_PARAMS_1(success, "fclose", stream); RETURN_CCTOR(success); }
tmihalik/cphalcon
ext/mvc/micro/collection.h
<reponame>tmihalik/cphalcon<filename>ext/mvc/micro/collection.h /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2013 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ extern zend_class_entry *phalcon_mvc_micro_collection_ce; PHALCON_INIT_CLASS(Phalcon_Mvc_Micro_Collection); PHP_METHOD(Phalcon_Mvc_Micro_Collection, _addMap); PHP_METHOD(Phalcon_Mvc_Micro_Collection, get); PHP_METHOD(Phalcon_Mvc_Micro_Collection, post); PHP_METHOD(Phalcon_Mvc_Micro_Collection, put); PHP_METHOD(Phalcon_Mvc_Micro_Collection, patch); PHP_METHOD(Phalcon_Mvc_Micro_Collection, head); PHP_METHOD(Phalcon_Mvc_Micro_Collection, delete); PHP_METHOD(Phalcon_Mvc_Micro_Collection, options); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_get, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_post, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_put, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_patch, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_head, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_delete, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_micro_collection_options, 0, 0, 2) ZEND_ARG_INFO(0, routePattern) ZEND_ARG_INFO(0, handler) ZEND_END_ARG_INFO() PHALCON_INIT_FUNCS(phalcon_mvc_micro_collection_method_entry){ PHP_ME(Phalcon_Mvc_Micro_Collection, _addMap, NULL, ZEND_ACC_PROTECTED) PHP_ME(Phalcon_Mvc_Micro_Collection, get, arginfo_phalcon_mvc_micro_collection_get, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, post, arginfo_phalcon_mvc_micro_collection_post, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, put, arginfo_phalcon_mvc_micro_collection_put, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, patch, arginfo_phalcon_mvc_micro_collection_patch, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, head, arginfo_phalcon_mvc_micro_collection_head, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, delete, arginfo_phalcon_mvc_micro_collection_delete, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_Micro_Collection, options, arginfo_phalcon_mvc_micro_collection_options, ZEND_ACC_PUBLIC) PHP_FE_END };